Site logo

Archived topic

Using generateblocks_query_loop_args to sort by post_views_count does not work

5 replies · Started by Elvis on November 24, 2022

Viewing posts 1–6 of 6

Hello,

I am trying to get the thing from title to work. Here is my gist. You can see it consistes of two files, one that sets the logic and another is a modified single.php file that runs the view counter (line 36).

In the logic file, I set the counter, and add it also as a column in the admin.
Then I try to modify the query block. And it does not work.

For testing purpose I have tried to apply sorting using pre_get_posts at the bottom, and when I set homepage as recent posts, and activate the pre_get_posts it works perfect. But I need this to work on select query blocks. But no luck. What am I doing wrong?

Thanks

Hi there,

try changing the orderby to declare its a numeric value ie.

'orderby' => 'meta_value_num',

Thanks David,
amazing, can you explain this modification please?

Ordering is working now, there is one interesting thing though.
Posts with no views (zero) do not show at all.
What would be the way to show also them (zero view posts) only last?

here is the function now:

function gb_query_by_views( $query_args, $attributes ) {
    if ( ! empty( $attributes['className'] ) && strpos( $attributes['className'], 'order_by_views' ) !== false ) {
        
        $query_args['post_type'] = 'post';
        
        $custom_args = array(
          'meta_key' => 'post_views_count',
          'orderby' => 'meta_value_num',
          'order' => 'DESC',
        );
    } else {
        return $query_args;
    }
    return array_merge( $query_args, $custom_args );
}
add_filter( 'generateblocks_query_loop_args', 'gb_query_by_views', 10, 2  );

Thanks a lot.

The meta_value would return the value as a string with alphabetical sorting. meta_value_num tells WP to treat the meta key value as a numeric value with number sorting.

Try setting your $count = 0; to $count = 1; - so all posts have at least one view.

Thanks man. This is pretty sweet. :D

Awesome - glad to be of help :)

This archived topic is closed to new replies.