Post Pic

Tomas asked “How to only get posts having a specific custom field? “

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

Dec 22 2008 13:20

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?

Dec 22 2008 13:23

This tip is awesome, thanks very much. I can see being able to get really creative with this idea.

Drew

Dec 22 2008 13:32

@Agolf Cartson: You can ask for recipes in the forum :)

Dec 22 2008 13:34

Oh… :) Yes obviously. I didn’t notice that you said that Tomas had asked in the forum. Sorry about that.

Dec 22 2008 22:15

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.

Dec 23 2008 01:04

@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 :)

Dec 24 2008 11:44

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:

Leave a Comment

* Name, Email, Comment are Required