0
votes

I am using Woocommerce, although my question relates to WP_Query in general. I am creating a custom WP_Query loop for bestselling products and I want to allow users to be able to sort the results by price, from high to low and low to high. The problem is in Woocommerce both _price and total_sales are meta fields and as far as I can tell I can only orderby 1 meta field in Wordpress loops. Is there a way around this?

My full code including some of my attempts is here, the most relevant code segment looks like as follows:

$queryArgs = array(
            'post_type' => 'product',
            'posts_per_page' => -1,
            'post_status' => 'publish',
            'meta_query' => array(
                array(
                    'key'           => '_visibility',
                    'value'         => array('catalog', 'visible'),
                    'compare'       => 'IN'
                )
            ),
            'meta_key' => '_price',
            'orderby' => array('meta_value_num' => $sortBy['terms'])
        );

The actual code is more complicated than this because it's built for a range of filtering and sorting options, but this is the gist of it and bestsellers is the only thing giving me issues because of the two meta_keys. I've read this but it doesn't apply to custom meta fields.

I've tried:

'meta_key' => '_price total_sales'

'meta_key => array('_price', 'total_sales')
'orderby' => array('meta_value_num' => $sortBy['terms'], 'meta_value_num' => 'DESC')

Nothing seems to work. I've also tried hooking onto the various WP_Query filters but the problem is this query is part of a dynamically generated loop so I can't 'hack' or hard-code anything.

1

1 Answers

1
votes

Use the meta query with arrays:

'meta_query' => array (
            array (
                'key' => '_visibility',
                'value'  => array('catalog', 'visible'),
                'compare' => 'IN'
             ),
            array (
                'key' => '_price',
                'value' => "VALUE WHAT YOU WANT, NOT ASC/DESC",
            )
        ),