WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Bug in get_post_meta ? (8 posts)

  1. Hello, Is this a bug in get_post_meta? This code should display the contents of the field "qanda" for the most recent post in the category "posts." But nothing shows. Using this wp_query with generating permalinks to the most recent post in "posts" works fine.

    This is run inside the loop:

    <?php $my_query = new WP_Query('category_name=posts&showposts=1'); ?><?php while ($my_query->have_posts()) : $my_query->the_post(); ?><?php echo get_post_meta($post->ID, "qanda", $single = true); ?><?php endwhile; ?>

    Thanks...

  2. Still trying to figure this out. If I hard code a post number, such as:

    <?php echo get_post_meta('602', "qanda", $single = true); ?>

    the value of the custom field "qanda" will echo. But the code won't take the post ID generated by the query loop.

    Any ideas? Thanks, Mark

  3. Still trying to figure this out. Why isn't get_post_meta getting the the dynamic post ID? Thanks, Mark

  4. Mark / t31os
    Moderator
    Posted 4 years ago #

    Use....
    $my_query->post->ID

    In the get_post_meta ...

    $post->ID will refer to the current post (in the normal loop) and not the one in your custom loop..

  5. Jeez, that was pretty simple. I tried $the_post->ID, but that next logical step in passing the post ID from my_query escaped me. And it works with multiple loops on the same page/post. Thanks much.

  6. Mark / t31os
    Moderator
    Posted 4 years ago #

    When you're writing code and passing variables around, to make it easier on yourself, dump the data you need to look at on the screen while testing...

    print '<pre>';
    print_r($var);
    print '</pre>';

    That will happily print out the contents of an array, object or string...

    The <pre> tags just format the code in a manner that is more readable..

    For example, to see what is stored in $my_query...

    print '<pre>';
    print_r($my_query);
    print '</pre>';

    Glad i was able to help anyway... ;)

  7. That's slick. Thanks. Someone on stackoverflow.com said I should dump variables using var_dump but it didn't work for some reason, as now I realize I had that syntax wrong, too:

    <?php print '<pre>';
    var_dump($my_variable);
    print '</pre>'; ?>
  8. Mark / t31os
    Moderator
    Posted 4 years ago #

    Prefer print_r to var_dump myself...

    I usually add a small function for the job if i'm testing stuff though, save having to add pre tags everytime...

    function printpre( $data ) {
      print '<pre>';
      print_r( $data );
      print '</pre>';
    }

Topic Closed

This topic has been closed to new replies.

About this Topic