Mathieu
Mathieu

Reputation: 761

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'); ?>  

Upvotes: 0

Views: 299

Answers (2)

rafiki_rafi
rafiki_rafi

Reputation: 1237

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);

Upvotes: 2

dardar.moh
dardar.moh

Reputation: 6725

There is a plugin, but it hasn't been updated in over 2 years. It may no longer be maintained or supported and may have compatibility issues when used with more recent versions of WordPress.

Upvotes: 0

Related Questions