Sorting posts by meta key and value

Posts related additional data are stored in a meta table called postmeta. Sometimes these meta data become very vital from your functionality point of view. Lets say we store the like counts of posts in terms of a meta key as _wti_like_count. This is fine as long as I am just using this to show the like count.

But can I use the same meta key to sort the posts by this value? Yes, we will discuss how we can sort the posts from a specific category. So in this case we will be modifying the category.php file inside the default theme folder since I am using the default theme.

<?php
// Get the requested category object
$category = $wp_query->get_queried_object();
$query = new WP_Query( array ( 'post_type' => 'post', 'cat' => $category->cat_ID, 'order' => 'DESC', 'orderby' => 'meta_value_num', 'meta_key' => '_wti_total_count' ) );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
/* Include the Post-Format-specific template for the content.
* If you want to overload this in a child theme then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'content', get_post_format() );
endwhile;
wp_reset_query();
else:
_e( 'Nothing Found', 'twentyeleven' );
endif;
?>

So we are doing the following things to achieve the functionality.

- Get the category id on the category page.

- Get the posts from the selected category.

- Loop through those posts and render them.

3 parameters are important here a) order b) orderby c) meta_key.

Since I need to show the posts by descending order of the like counts, I have used DESC value for order parameter. I want to consider the ordering based on meta numeric value, I have used meta_value_num for orderby parameter. I want to order with respect to _wti_like_count meta key so I have used the same for meta_key parameter. Thats all and you will see the posts sorted by the like count.

Note:

- If you need to sort the posts by unlike count, then use _wti_unlike_count for meta_key parameter.

- If you need to sort the posts by total count (like – unlike), then use _wti_total_count for meta_key parameter.

- if you want to use this feature for WTI Like Post plugin, then its available only for the pro version since in this version meta data are stored.

- For more details on WP_Query and its meta key/value parameters, please visit here.

Happy Coding :)

Leave a Reply

©2012WebTechIdeas. All rights reserved.