This article shows How to retrieve and display the most popular posts by total comments on your WordPress template. A PHP function below will use the get_results function to run a SQL query to the WordPress posts table to get the top posts with highest comments.
1. Get WordPress Top Posts With Highest Comments
We can place the PHP function below in the sidebar.php file in the WordPress template folder or somewhere else such as footer.php or functions.php file.
<?php function popularPosts($num) { global $wpdb; $posts = $wpdb->get_results("SELECT comment_count, ID, post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , $num"); foreach ($posts as $post) { $id = $post->ID; $title = $post->post_title; $count = $post->comment_count; if ($count != 0) { $popular .= '<li>'; $popular .= '<a href="' . get_permalink($id) . '" title="' . $title . '">' . $title . '</a> '; $popular .= '</li>'; } } return $popular; } ?> |
2. Usage
Simple call the popularPosts function and pass the number of returned posts.
<div id="tab_popularPosts"> <ul> <?php echo popularPosts(10); ?> </ul> </div> |
