phpwordpresscomments

Order Wordpress posts by most recent comment


I tried many things but impossible to get it works.

I finally deleted my try

Is there a plugin instead ?

SOLUTION :

In your function.php :

/** 
 * Comment_pre_save filter updates post_modified date
 * to coincide with new comments. Since posts are ordered by 
 * post_modified, this will 'bubble' up more active posts to the top
 */ 
add_filter('preprocess_comment', 'update_post_modified');

function update_post_modified($comment_data){
    global $wpdb;
    $wpdb->update( 
        $wpdb->posts, 
        array( 
            'post_modified' => current_time('mysql'),   // string
        ),
        array( 'ID' => $comment_data['comment_post_ID'] ), 
        array( 
            '%s'
        ), 
        array( '%d' ) 
    );
    return $comment_data;
}

In your index.php:

<?php $posts=query_posts($query_string . '&orderby=modified'); ?>  

Solution

  • This is a bit a of a hack, but I had to do the same thing for one of my projects. I ended up updating a post's "post_modified" field every time a new comment was made on a post using the preprocess_comment filter:

    /** 
     * Comment_pre_save filter updates post_modified date
     * to coincide with new comments. Since posts are ordered by 
     * post_modified, this will 'bubble' up more active posts to the top
     */ 
    add_filter('preprocess_comment', 'update_post_modified');
    
    function update_post_modified($comment_data){
        global $wpdb;
        $wpdb->update( 
            $wpdb->posts, 
            array( 
                'post_modified' => current_time('mysql'),   // string
            ),
            array( 'ID' => $comment_data['comment_post_ID'] ), 
            array( 
                '%s'
            ), 
            array( '%d' ) 
        );
        return $comment_data;
    }
    

    Edit:

    Forgot to add one bit, wherever you have your post loop, make sure you order it by the modified date, otherwise this hack won't work. For example:

    global $wp_query;
    $args = array_merge( $wp_query->query, array( 'orderby' => 'modified' ) );
    query_posts($args);