List Popular Posts By Comment Count

In this post, i’ll show you how to create your own new WP_Query & custom loop.

Your new WP_Query will fetch specific posts from your database based on the parameters you add to the code and display them in a new custom loop.

You can then output the list anywhere using a variety of methods, one of which is get_template_part() in a custom function.

Here’s the final result using a few lines of CSS to style the output.

list specific posts

WP Query Parameters

The code in this tutorial, includes 3 parameters:

'orderby' => 'comment_count',
'posts_per_page' => 3,
'post__not_in' => $sticky
  1. The 1st parameter orders the posts by comment count displaying the most commented post first.
  2. The 2nd parameter determines how many posts to display in the list which is 3.
  3. The 3rd parameter excludes any sticky posts from the list.

Code Installation

  1. Create a new file named wpsites.php using a code editor like Notepad++ and copy & paste the PHP code from the Gist labelled wpsites.php into the new file then upload it to your child themes root directory.
  2. Copy the code from the view raw link in the Gist labelled functions.php and paste it at the end of your child themes functions.php file.
  3. Copy the CSS code from the Gist labelled style.css and paste it at the end of your child themes style.css file before the start of your Media Queries section.

Custom Function

The custom function is very simple and includes a conditional tag to limit the display of your posts to single posts only and a hook for positioning the display after the entry content.

The function also includes get_template_part which loads the wpsites.php file based on the conditional tag and hook. You can also reuse the code in the wpsites.php file directly in files or other custom functions.

Related Posts


Comments

2 responses to “List Popular Posts By Comment Count”

  1. Ramon Fincken Avatar
    Ramon Fincken

    I wrote a patch the other night to be able to query posts based on amounts of comments, please test it over here: https://core.trac.wordpress.org/ticket/28399

    1. Brad Dalton Avatar
      Brad Dalton

      Ok Thanks Ramon.

Leave a Reply

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.