Most Discussed Posts Feed
Publishes a second feed at /feed/popular/ listing your posts with the most comments from recent months, handy for "popular this month" newsletters and sidebar widgets on other sites.
Opens WPIDE on
Code
// Feed name: the feed lives at /feed/popular/ (or ?feed=popular with plain permalinks).
$wpide_popular_feed_name = 'popular';
// Only count posts published in the last number of days (0 = all time) and how many to list.
$wpide_popular_feed_days = 90;
$wpide_popular_feed_items = 10;
add_action( 'init', function () use ( $wpide_popular_feed_name, $wpide_popular_feed_days, $wpide_popular_feed_items ) {
add_feed( $wpide_popular_feed_name, function () use ( $wpide_popular_feed_days, $wpide_popular_feed_items ) {
$cache_key = 'wpide_popular_feed_' . md5( $wpide_popular_feed_days . '|' . $wpide_popular_feed_items );
$ids = get_transient( $cache_key );
if ( ! is_array( $ids ) ) {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => max( 1, (int) $wpide_popular_feed_items ),
'orderby' => array( 'comment_count' => 'DESC', 'date' => 'DESC' ),
'has_password' => false,
'ignore_sticky_posts' => true,
'no_found_rows' => true,
'fields' => 'ids',
);
if ( $wpide_popular_feed_days > 0 ) {
$args['date_query'] = array( array( 'after' => absint( $wpide_popular_feed_days ) . ' days ago' ) );
}
$ids = get_posts( $args );
set_transient( $cache_key, $ids, HOUR_IN_SECONDS );
}
$GLOBALS['wp_query'] = new WP_Query( array(
'post_type' => 'post',
'post__in' => $ids ? $ids : array( 0 ),
'orderby' => 'post__in',
'posts_per_page' => count( $ids ) ? count( $ids ) : 1,
'ignore_sticky_posts' => true,
'no_found_rows' => true,
) );
add_filter( 'get_wp_title_rss', function ( $title ) {
return $title . ' – Most discussed';
} );
load_template( ABSPATH . WPINC . '/feed-rss2.php' );
} );
} );
Notes
After activating, visit Settings > Permalinks and click Save so /feed/popular/ works; the list is cached for an hour.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.