Site logo

Archived topic

Query loop with most read items

1 reply · Started by Kees on October 19, 2022

Viewing posts 1–2 of 2

Hi,

We have a query loop on the homepage with blogs. But we would like to order the blogs on most read. How do we do that? We don't have that option.
Would be nice to have this working.

Let me know.

Regards,
Niek

Hi there,

WP doesn't store any meta data relating to post views by default.
Which is why there is no option for it.

To do it would require custom development.
Another user did the following which may work for you:

1. Function to create a post_views_count meta key and store the post count value:

https://stackoverflow.com/questions/7425789/how-to-sort-posts-sort-by-views-using-post-views-count-function

2. Use the generateblocks_query_loop_args filter to merge in your own meta_key sort query using this snippet:


add_filter( 'generateblocks_query_loop_args', function( $query_args, $attributes ) {
	// Check your logic to apply the filtering only to specific loop
	if (
		! empty( $attributes['className'] ) &&
		strpos( $attributes['className'], 'my-class-name' ) !== false &&
		is_home() &&
		! is_admin()
	) {
		// Merge the current $query_args which contains arguments defined in the editor with your ordering arguments
		return array_merge( $query_args, array(
			'meta_key' => 'post_views_count',
			'orderby' => 'meta_value_num',
			'order' => 'desc',
		) );
    }

    return $query_args;
}, 10, 2 );

Note this line:

strpos( $attributes['className'], 'my-class-name' ) !== false && you can change the my-class-name to your own custom CSS class that you need to add to the Query Loops Grid block > Advanced > Additional CSS CLass(es) field.

This archived topic is closed to new replies.