Site logo

[Support request] Using generateblocks_query_loop_args to sort by post_views_count does not work

Home Forums Support [Support request] Using generateblocks_query_loop_args to sort by post_views_count does not work

Home Forums Support Using generateblocks_query_loop_args to sort by post_views_count does not work

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #2430716
    Elvis

    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

    #2430752
    David
    Staff
    Customer Support

    Hi there,

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

    'orderby' => 'meta_value_num',

    #2431511
    Elvis

    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.

    #2431525
    David
    Staff
    Customer Support

    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.

    #2431530
    Elvis

    Thanks man. This is pretty sweet. 😀

    #2432656
    David
    Staff
    Customer Support

    Awesome – glad to be of help 🙂

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.