Make Jetpack infinite scrolling work with custom field sort

I tried to contact Jetpack but they wouldn’t help

Hi,
I have a custom field “view_count” for my WooCommerce products.

When trying to sort an archive page by it , this code works:

add_filter('woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args');

function custom_woocommerce_get_catalog_ordering_args($args)
{
    $orderby_value = isset($_GET['orderby']) ? wc_clean($_GET['orderby']) : apply_filters('woocommerce_default_catalog_orderby', get_option('woocommerce_default_catalog_orderby'));

    if (!is_search()) {
        if ('view_count' == $orderby_value) {
            $args['orderby']  = ['meta_value_num' => 'DESC'];
            $args['meta_key'] = 'view_count';
        }
    }

    return $args;
}

But when trying to make the infinite-scroll work with it, the following code produces unexpected results: it doesn’t order by the custom field and it duplicates products.

add_filter('infinite_scroll_query_args', 'jetpack_infinite_scroll_query_args', 20);

function jetpack_infinite_scroll_query_args($args)
{
    $orderby_value = isset($_GET['orderby']) ? wc_clean($_GET['orderby']) : apply_filters('woocommerce_default_catalog_orderby', get_option('woocommerce_default_catalog_orderby'));

    if (!is_search()) {
        if ('view_count' == $orderby_value) {
          $args['orderby']  = ['meta_value_num' => 'DESC'];
          $args['meta_key'] = 'view_count';
        }
    }

    return $args;
}

I tried to remove the “if” conditions and leave only

$args['orderby']  = ['meta_value_num' => 'DESC'];
$args['meta_key'] = 'view_count';

and got the same results.

Is it a bug or am I missing something?
Thanks,Asaf

Leave a Reply

Your email address will not be published. Required fields are marked *