简体   繁体   中英

How to select WooCommerce products by post_meta and order them

I'm using the following code to select products with the following post_meta keys: _product_new , _product_almost_new and _product_old .

My code:

add_action( 'woocommerce_product_query', 'custom_vtp_shop_order' );

function custom_vtp_shop_order($q){
    if ( ! $q->is_main_query() ) return;
    if (! is_admin() && (is_shop() || is_archive) ) {

        $q->set( 'tax_query', array(array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => array( 'Sold', 'Service' ),  
            'operator' => 'NOT IN'
        )));

        $q->set('meta_query', array(array(
            'relation' => 'OR',
                'product_new' => array(
                    'key' => '_product_new',
                    'value' => '1',
                ),
                'product_almost_new' => array(
                    'key' => '_product_almost_new',
                    'value' => '1',
                ), 
                'product_old' => array(
                    'key' => '_product_old',
                    'value' => '1',
                )
            )));

        /*THIS HAS NO EFFECT*/
        $q->set('orderby', array(array( 
                'product_new' => 'DESC',
                'product_old' => 'DESC',
                'product_almost_new' => 'DESC',
            )        
        ));

    }

}

I want the products to then be displayed in the following order:

  1. product_new
  2. product_old
  3. product_almost_new

I am using $q->set('orderby', array(......) but this is having no effect. My products are ALWAYS being ordered product_old , product_almost_new , product_new .

Any ideas why my 'orderby' is not working? Any help is appreciated.

You did all right except one thing. You have used array in array in orderby which is not correct. Here is how it should look like:

$q->set('orderby', array(
                'product_new' => 'DESC',
                'product_almost_new' => 'DESC',
                'product_old' => 'DESC',
            )        
        );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM