Sometimes you only want to show posts that you’ve added a specific custom field to. For instance, lets say you write book and movie reviews and for each you give them a custom field “review_type” with the value set to either “book” or “movie”. So how would you show posts that are only movie reviews? Easily!

A typical post loop begins like this:

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

We’re going to add a simple query_posts function immediately above the loop code. In our scenario it would look like this:

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

We’ve now restricted posts in the loop to movie reviews. Easy! Read the WP Codex article for more advanced uses of the query_posts function.


Reply

Tomas Buteler

May 6, 20093:30 am

Just followed here from Wp-Recipes…

This is a great function, thanks for sharing!

Just a heads-up, though, which you can correct me if I’m wrong: 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.

Cheers!

Reply

Jerry

July 23, 200911:29 am

John,

I’ve tested this code and it works great … however I would like to be able to sort the order of the posts as they appear on the page … i have a meta_key called “player-jersey-number” that I would like to sort the entries as they are displayed by the player’s number, not when post created.

Reply

justgage

August 26, 20093:32 pm

Think you just saved my bacon =D

Reply

pete

October 2, 20092:03 pm

Hi John… almost what i was looking for. How would would this be updated if I only want to show posts that I’ve added 2 or 3 specific custom fields to

thanks
Pete

Reply

Jennifer R

July 13, 20102:50 pm

Thanks, your code help me alot :)

Comment on this post:

License: By commenting you are granting me a perpetual, non-exclusive license to reproduce, paraphrase, and display your words, name, and/or website on this domain. All comments subject to moderation, editing, or deletion at my discretion.

Important: Unfortunately, I'm unable to offer support via comments. However, feel free to hire me.

Entering code?

(optional)