The Below code works for simple products but fails for products with variance
add_filter( 'woocommerce_get_catalog_ordering_args', 'sort_by_width_woocommerce_shop' );
function sort_by_width_woocommerce_shop( $args ) {
global $wp_query;
$orderby_value = isset( $_GET['orderby'] ) ? wc_clean( (string) wp_unslash( $_GET['orderby'] ) ) : wc_clean( get_query_var( 'orderby' ) );
if ( 'width-asc' == $orderby_value ) {
$args['orderby'] = 'meta_value_num';
$args['order'] = 'ASC';
$args['meta_key'] = '_pm_width_inches';
$args['meta_type'] = 'NUMERIC';
$args['type'] = 'product';
}
else if('width-desc'== $orderby_value){
$args['orderby'] = 'meta_value_num';
$args['order'] = 'DESC';
$args['meta_key'] = '_pm_width_inches';
$args['type'] = 'product';
}
/* ?>
<?php echo "<ul>". var_dump( $args['meta_key'] )."</ul>";?>
<?php */
return $args;
}
// 2. Add new product filter to Sorting dropdown
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby' );
function custom_woocommerce_catalog_orderby( $orderby ) {
unset($orderby);
$orderby['price'] = __('Price: Low to High');
$orderby['price-desc'] = __('Price: High to Low');
$orderby['popularity'] = __('By Popularity');
$orderby['date'] = __('Newest Arrivals');
$orderby['width-asc'] = __('Size: small to large');
$orderby['width-desc'] = _('Size:large to small ');
/* ?>
<?php echo "<ul>".var_dump($orderby)."</ul>";?>
<?php */
return $orderby;
}
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby', 20 );