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 can be seen 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_valuein 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…
You code seems to work just fine. Only thing was a <th> you didn’t close. Your problem might be somewhere else?
@kim: Thanks for the response, and good catch on the <th> error!
So this worked for you?? It absolutely refuses to work on my test site, except on the single post page template (where there is no new WP_query). Then it works just fine. Same post data, same custom fields. Same code even! I copied and pasted it.
Guess I’m gonna have to fire up a fresh WordPress install and re-test it there…
Yes it works. I tested it on page.php just after the comments_template(…) in the Twenty Eleven 1.2 theme. It shows all post titles and the meta values on a couple of posts where I entered them as normal custom fields.
That is astonishing, because I’ve tested it on two different WP installs (different themes, one very minimal) and I can’t even get the $post object to return the custom fields.
I used this to see what was being returned by my WP_Query:
Global $post; echo "<pre>"; print_r($post); echo "</pre>";
…and saw no sign of my custom fields. Yet I can get them to appear on a single post by adding the same code to the page template.
Thank you for taking the time to help me troubleshoot this, btw! I really do appreciate it. I’m trying to add this functionality to one of my WP plugins, per a user request.
@kim: Would you mind terribly testing out this plugin: http://mynewsitepreview.com/plugins/sorttablepost_v4.0beta.zip
[sorttablepost meta="Custom Field Key,Another Custom Field Key,Yet Another" nothumb="true" nocats="true" notags="true"]should output a table that lists all of your post titles, post dates, and whatever custom fields you identify in the meta option.
Thanks in advance…
Wp_query does not return the meta data on its own as far as I know.
The plugin didn’t work (didn’t get the meta values). I tried to check the data that was used by get_post_meta(); The meta keys seems ok, but when I tried to echo $post->ID, I got nothing. Try to add
global $post;just after the loop starts.
- The topic ‘Can WP_Query return custom field post meta?’ is closed to new replies.