Is it possible to sort products by attribute or product dimension? I have products with an attribute called "Undergr." (the values are numbers, different value for each product) and I'm trying to have an option to sort by this value ascending and/or descending.
I found the code snippet on WooCommerce Document that shows how to apply custom sorting options:
/**
* This code should be added to functions.php of your theme
**/
add_filter('woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args');
function custom_woocommerce_get_catalog_ordering_args( $args ) {
if (isset($_SESSION['orderby'])) {
switch ($_SESSION['orderby']) :
case 'date_asc' :
$args['orderby'] = 'date';
$args['order'] = 'asc';
$args['meta_key'] = '';
break;
case 'price_desc' :
$args['orderby'] = 'meta_value_num';
$args['order'] = 'desc';
$args['meta_key'] = '_price';
break;
case 'title_desc' :
$args['orderby'] = 'title';
$args['order'] = 'desc';
$args['meta_key'] = '';
break;
endswitch;
}
return $args;
}
add_filter('woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby');
function custom_woocommerce_catalog_orderby( $sortby ) {
$sortby['title_desc'] = 'Reverse-Alphabetically';
$sortby['price_desc'] = 'Price (highest to lowest)';
$sortby['date_asc'] = 'Oldest to newest';
return $sortby;
}
I've tried using the meta_value_num example, and change the meta_key, but nothing I've tried so far is working and I don't understand why.
A possible alternative is to sort by dimensions, either length, height or width, or all three of them. Is that possible?
This is really driving me crazy, any help is greatly appreciated!