wordpresscustom-fields

Can WordPress WP_Query return custom field post meta?


For some reason, I cannot get WP_Query to return the custom field values of posts. I can get the post thumbnails using get_the_post_thumbnail($post->ID, array(50,50)), but I cannot get the custom field data using get_post_meta($post->ID, $key, true).

A stripped-down version of what I'm trying to do:

<?php
    $keys = array('Show Date','Birth Year','Origin');

    echo '<table>';
    echo '<tr><th>Title</th>';
    foreach( $keys as $key ) {
        echo '<th>' . $key . '<th>';
    }
    echo '</tr>';

    $myquery = new WP_Query( 'post_type=post' );
    if( $myquery->have_posts() ) : while( $myquery->have_posts() ) : $myquery->the_post();

        $title = get_the_title();
        echo '<tr><td>' . $title . '</td>';

        $values = array();
        foreach( $keys as $key ) {
            $values[] = get_post_meta($post->ID, $key, true);
        }
        foreach( $values as $value ) {
            echo '<td>';
            echo $value;
            echo '</td>';
        }
        echo '</tr>';

    endwhile; endif;

    echo '</table>';
?>

Also available here:
http://pastebin.com/at8S2THs

Even with all non-essential code removed, I cannot make this work. I know you can use parameters like meta_key and meta_value in a query to narrow down the results, but I just want to display all values for the keys I specify, if they exist, for each post.

Any help would be greatly appreciated...

** SOLUTION FOUND **

Just needed to add global $post; after the start of the loop. Thanks to @Kimikaze on the WP support forum for providing the solution!


Solution

  • When I can't find the data I need in wordpress, I always find it helpful to print the Global $post object to screen, so I can see if my data is making it to the page.

    Global $post;
    echo "<pre>";
     print_r($post);
    echo "</pre>";
    

    All the helper methods or "hooks" are usually just interacting with this (or another) global object. Check the output of this on $post (and maybe your $values array) for data you're looking for and if it's there, you can just reffer to it directly, like the post title for example

    $post->title
    

    Another thought, The third parameter of get_post_meta() makes it return a single string when set to true, what do you get when it's set to false?