Code Snippets Gallery
Custom Loop/Query Based on Custom Fields
This snippet enables you to make a custom loop 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:
<?php
$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; ?>
This is great! What if you want to limit the loop to 5 posts/pages?
Okay, that was easy. Just added LIMIT 4 to the query details…
hmm..is it support wordpress 2.9???
Great stuff, using it in several places in one of my wp templates.
In addition to this, is there a way to query mulitiple custom fields and print the “merged” results?
Isn’t this the same result you’d obtain using wp_query?
Something like this:
http://wordpress.pastebin.com/uJDdsiCw
I used this reference:
http://codex.wordpress.org/Template_Tags/query_posts#Custom_Field_Parameters
but haven’t tried it yet.
I’ve been trying to figure out, how to show posts from a specific category, if the page template being viewed has a custom field value with the same name.
ie. a custom field value is present, and posts in a category with the same name as that custom field value are shown.