Post Pic

Easily get posts with a specific custom field/value on your WordPress blog

Ever wanted to be able to only get the list of posts which have a specific custom field key as well as a specific value? If yes, just read on. Our friend John Kolbert have this short, but useful recipe for you.

To achieve this recipe, simply find the loop and add the query_posts() function just above, as in the example below:

<?php query_posts('meta_key=review_type&meta_value=movie');  ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

You'll get the list of post having review_type as a custom field key and movie as a value. Just change theses values to fit your needs.

Credits goes to John Kolbert for this great piece of code!

18 Responses

May 04 2009 17:22

Thanks jbj :)

May 04 2009 20:04

Another great tip, nice on JBJ.

May 04 2009 20:35

what if there are more than one key/value?

May 05 2009 02:16

Hello admin, please tell me how to add a post thumbnail without a plugin. Thank you very much!

May 05 2009 20:29

Thanks.

May 06 2009 11:26

This is a good one, though I tried to use it a while back and found out that it wasn’t good for the type of Custom Field I had created. I figured instead of doing ‘yes’ or ‘no’ meta values for my fields, I use the classic binary ‘0′ and ‘1′, only to find out that calling ‘meta_key=whatever&meta_value=0′ completely ignores the second parameter…

If you need to fetch custom fields whose value needs to be ‘0′, you’ll have to use a Custom SELECT query, instead.

I also never figured out how to pass multiple meta_keys and their respective values using just the query_post() function above, so anyone trying to do that can resort to SELECT as well.

May 08 2009 07:13

Thanks for another great tip!

May 19 2009 11:51

hello,

how to count the total number of posts with the specific value of custom field?

bye

Jun 23 2009 12:26

if i want to search multiple meta field values then what should i do ??

Jun 27 2009 00:11

Thanks! This helped me!

Dec 07 2009 19:52

Hi!

In my blog a have this query:
query_posts($query_string.’&showposts=10&meta_key=TEST’);

ok, it works and bring to me 10 posts with TEST in custom field, but my doubt is how i brings only posts with empty custom fields, because i have 2 queries, one show just TEST posts, and other must show all less first query, avoinding duplicated posts.

can u help me? hugs!

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required