Monday, July 8, 2013

How to add a custom Loop/Query based on custom fields in Wordpress

This php code enables you to make a custom loop (query based) that is purely based on custom-fields. Not dependent on any category or tag. This is not (yet) possible with query_posts() or WP_Query(), so we here utilize a direct $wbdb-call:

$querydetails = "
SELECT wposts.*
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
WHERE wposts.ID = wpostmeta.post_id
AND wpostmeta.meta_key = 'readmoretext'
AND wpostmeta.meta_value = 'Go check this out'
AND wposts.post_status = 'publish'
AND wposts.post_type = 'post'
ORDER BY wposts.post_date DESC
";

$pageposts = $wpdb->get_results($querydetails, OBJECT)

First we select any WordPress Posts that contain "meta data" (custom fields). We then add a few conditions. For example, the key should be "readmoretext", another condition is that the value of the custom field needs to be "Go check this out". Also, it needs to be published post, it needs to be an actual Post (not a Page), and in lastly in descending order.

You can remove, add or duplicate/change any of these AND conditions to get exactly the thing you need. (for example, all Posts that have a custom field called "mood", then get rid of the *. meta_value-line and then you'll get all the posts that have a "mood" set regardless of it's value.

 After you've run the query, you can run a loop to output the results:

<?php if ($pageposts):
foreach ($pageposts as $post):
setup_postdata($post); ?>

// Make your loop here. For example :
<div <?php post_class(); ?>> id="post-<?php the_ID(); ?>">
<h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
<?php the_content(); ?>
</div>

<?php endforeach;
endif; ?>

Disqus Comments