Get wordpress posts having a specific custom field

December 23, 2008 · Print This Article

How we can only get posts that have a certain custom field.

As far as we know, this question has been asked many times on several blogs and WordPress forums.

It 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

Your choice for site templates and wordpress themes


One Response to “Get wordpress posts having a specific custom field”

  1. cdmckay on January 10th, 2010 11:58 am

    I have to say, this code is pretty useless. What if I had a database with 1,000 posts? This code would require me to pull down all 1,000 posts and check the custom field on every post.

Got something to say?

You must be logged in to post a comment.