I want to encourage my authors to provide feedback to new posts that have not received enough exposure. To do this, I want to add a box to WP-Admin that lists the top 3 latest posts (from the past two days) with least comments.

In terms of table structure, I'm thinking something like this answer for listing latest posts.

All you need is a table with class='widefat' and get_posts(). Then you run through the results (if there are any) and print the table rows.

The code works great but his was for listing the latest 10 posts, my question is how to list the latest posts with least comments?

  • Where do you want to put the list?
    – s_ha_dum
    Jun 7 '13 at 16:42
  • In various places in WP-Admin. For example, I use the code in the answer that I linked above in a custom page and it works great. I'm thinking some alteration to that code would be most feasible (adding a filter for least commented post if possible).
    – Christine Cooper
    Jun 7 '13 at 16:45
  • It is hard to write code for "various places". If what you've got "works great", then what is the question?
    – s_ha_dum
    Jun 7 '13 at 16:48
  • 1
    Apologies, I should have been more specific s_ha_dum, let's set it to the Dashboard as Toscho did in that answer. I said that his code worked great but his was for listing the latest 10 posts, my question is how I list the latest posts with least comments. I hope that I've explain this well this time, although I am essentially just repeating my original question.
    – Christine Cooper
    Jun 7 '13 at 16:57
  • you have to use $wpdb with probably some JOIN in your query. See documentation
    – JMau
    Jun 7 '13 at 18:26

I managed to figure it out. So, get_posts() uses WP_Query() and we can use the example in the documentation to filter the dates.

Now for the comments, that is easy, we just add the parameter 'orderby'=>'comment_count'. Also to note, when filtering get_posts(), we will need to disable suppress_filters.

Let's filter the time first:

function filter_where( $where = '' ) {
    // posts in the last 2 days
    $where .= " AND post_date > '" . date('Y-m-d', strtotime('-2 days')) . "'";
    return $where;

And now let's get the posts:

add_filter( 'posts_where', 'filter_where' );
    $query = get_posts(
        array (
         'numberposts' => 2,
         'suppress_filters' => false,
         'post_type'   => array ( 'post' )
remove_filter( 'posts_where', 'filter_where' );

That will give you the top least commented posts from the past 2 days.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.