How to Display a WordPress Post Like Count Ranking
If you've implemented a post 'like' feature, the next step is often to display a ranking of posts based on their like count. This tutorial explains how to achieve this.
Implementation Principle
The method is similar to querying for recent or popular posts. The key is to query posts using a custom meta field that stores the like count. Assuming your like system saves the count in a meta field named dotGood, you can use the following code.
Code Example
Here is a basic implementation using WP_Query, which is the recommended method over query_posts().
<?php
$liked_posts_args = array(
'post_type' => 'post',
'posts_per_page' => 10,
'meta_key' => 'dotGood',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'ignore_sticky_posts' => true
);
$liked_posts_query = new WP_Query( $liked_posts_args );
if ( $liked_posts_query->have_posts() ) : ?>
<ul>
<?php while ( $liked_posts_query->have_posts() ) : $liked_posts_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?> (Likes: <?php echo get_post_meta( get_the_ID(), 'dotGood', true ); ?>)
</a>
</li>
<?php endwhile; ?>
</ul>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
How to Use This Code
Place this code block in your theme template file where you want the ranking to appear, such as sidebar.php or a custom page template. You can adjust the posts_per_page argument and style the output (the <ul> and <li> tags) to match your theme's design.
Important Notes
- Meta Key: Ensure the
meta_keyvalue ('dotGood'in this example) matches the key your like plugin or custom code uses to store the count. - Performance: For large sites, consider caching the query results or using a transient to avoid performance issues from frequent meta queries.
- Alternative: If you are using a popular like plugin, check if it provides built-in shortcodes or widgets for displaying rankings, which might be easier to implement.