Order by attribute and price in woocomerce

Viewed 39

I'm trying to order my products by price and attribute

First, attribute sort and after price sort

First of all I created a attribute with the slug tp and after reasearches on internet I found that meta_value_num is the option to get a sort by price

meta_query let me sort by multiple meta_key

I've tried both $args['orderby'] = 'meta_value'; $args['orderby'] = array('attribute','price');

This is my code but he's not working

add_filter( 'woocommerce_catalog_orderby', 'add_custom_sorting_options' );

function add_custom_sorting_options( $options ){
    $options[ 'PMDefault' ] = 'DefaultPM';
    return $options;
}

add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_product_sorting' );
function custom_product_sorting( $args ) {
    $orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
    if( 'PMDefault' == $orderby_value ) {
        $args['meta_query'] = array(
            'attribute' => array(
                'key' => '_product_attributes',
                'value' => 'tp',
                'compare' => '=',
            ),
            'price' => array(
                'key' => '_price',
                'compare' => 'EXISTS',
                'type' => 'NUMERIC',
            ),
        );
        $args['orderby'] = 'meta_value';
        $args['order'] = 'desc';
    }
    
    return $args;
}
0 Answers
Related