I'm trying to build a list of posts, sorted by their most recent comments (not by comment count, but comment date). The list would display the post title, featured image, but not necessarily the comment itself. The idea is to give more attention to the posts that people already find most interesting, and to keep the front page of the site alive and changing.
I've found an article that talks about this, but it's 11 years old, and I'm not exactly sure how to replicate this in Toolset.
https://stackoverflow.com/questions/698438/ordering-wordpress-posts-by-most-recent-comment
There are several widget plugins that list "popular posts", but they all seem to query comment count instead of comment date.
My site lists songs, so the name of the list would be "Recently commented songs", for example. The site doesn't use custom post type for the songs, though. There was no need, since there is no other content, other than the songs.
hidden link
Hello and thank you for contacting the Toolset support.
While the solution suggested on the thread you referred might still be working with WordPress, but it can't integrate easily into Toolset. All the solutions suggest building your own SQL query, that would be tricky to integrate it with Toolset view query.
The cleanest solution I can imagine is the following:
1. Add a date field to your posts which will hold the date of the last comment. You won't need to include this field in your views or forms. Let's say the field slug is "last-comment-time".
2. Add a custom PHP code to update this field each time a comment is submitted.
3. Create a view that will display posts ordered by that custom field.
https://toolset.com/documentation/user-guides/views/filtering-views-by-custom-fields/
The following custom code can work for step (2), add it to your theme's functions.php or to Toolset->Settings->Custom code:
// update post last comment field when a comment is approved
function update_last_comment_field( $comment_ID, $comment_approved ) {
// Only when the comment is approved.
if( 1 === $comment_approved ){
// get the comment object.
$comment = get_comment( $comment_ID );
// get the post ID
$post_id = $comment->comment_post_ID ;
// get the post object
$post = get_post( $post_id );
// only for post type "post"
if ( $post->post_ype == "post" ) {
// update custom field. Toolset field slug is prefixed with "wpcf-"
update_post_meta( $post_id, 'wpcf-last-comment-time', time() );
}
}
}
// Execute this action when a comment is saved
add_action( 'comment_post', 'update_last_comment_field', 10, 2 );
Note that the meta key for the field is prefixed by "wpcf-" "wpcf-last-comment-time".
Read more about this here:
- https://developer.wordpress.org/reference/hooks/comment_post/
- https://developer.wordpress.org/reference/functions/get_comment/
- https://developer.wordpress.org/reference/functions/update_post_meta/
I hope this helps. Let me know if you found any issues.