
One of WpRecipes readers, Tomas, asked in the forum how he can only get posts that have a certain custom field. As far as I know, this question has been asked many times on several blogs and WordPress forums. Here is a solution to Tomas question.

One of WpRecipes readers, Tomas, asked in the forum how he can only get posts that have a certain custom field. As far as I know, this question has been asked many times on several blogs and WordPress forums. Here is a solution to Tomas question.
The answer to Tomas question is quite simple. What I've done is simply using a normal loop (That you can enhance with query_post() for exemple) and then, using a conditional instruction to check out if the post have the esired custom field.
<?php if (have_posts()) :
while (have_posts()) : the_post();
$customField = get_post_custom_values("img");
if (isset($customField[0])) {
//Custom field is set, display post info
the_title();
the_excerpt();
}
endwhile;
endif;
?>
10 Responses
I don’t know how it have taking me so long to find this blog. So many great answers to questions that I’ve had. I do still have one question though: Where do you ask the questions that is being answered in these posts?
This tip is awesome, thanks very much. I can see being able to get really creative with this idea.
Drew
@Agolf Cartson: You can ask for recipes in the forum
Oh…
Yes obviously. I didn’t notice that you said that Tomas had asked in the forum. Sorry about that.
Ok, I could be wrong but I’m not sure this will get ALL posts with the “img” custom field. Won’t it only get the recentmost 10 posts (or however many posts you are displaying on your homepage)?
To get ALL posts, I think you might have to do a database query.
@raj: Interresting comment! In fact, if you defined 10 posts in your WP options, and use the code “as it”, it will only get the 10 most recent posts.
But you can use that code with the query_post() function to control how many posts you want to retrieve, specific categories, etc
Thanks, by the way! I could finally get the results I wanted from the code above. I actually wanted to put it inside the query_post() function, but I liked your solution better, and it led to a host of other changes that made my code much simpler…
Thanks!
Tomas
Trackbacks: