Query Loop Block: Most Discussed Posts
Sorts any Query Loop block with the class "wpide-most-commented" by number of comments, for a "Most discussed" list without a plugin.
Opens WPIDE on
Code
$wpide_query_popular = array( 'active' => false );
add_filter( 'pre_render_block', function ( $pre, $parsed ) use ( &$wpide_query_popular ) {
if ( 'core/query' === $parsed['blockName'] ) {
$classes = isset( $parsed['attrs']['className'] ) ? ' ' . $parsed['attrs']['className'] . ' ' : '';
$wpide_query_popular['active'] = false !== strpos( $classes, ' wpide-most-commented ' );
}
return $pre;
}, 10, 2 );
add_filter( 'query_loop_block_query_vars', function ( $query ) use ( &$wpide_query_popular ) {
if ( ! $wpide_query_popular['active'] ) {
return $query;
}
$query['orderby'] = array( 'comment_count' => 'DESC', 'date' => 'DESC' );
$query['ignore_sticky_posts'] = true;
return $query;
} );
Notes
Add wpide-most-commented to the Query Loop's Additional CSS class(es) and turn off "Inherit query".
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.