public
Last active

WooCommerce - Custom sorting options (asc/desc)

  • Download Gist
gistfile1.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
/**
* 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;
}

Can you sort by custom sort options that include meta_key, meta_value, and meta_compare. Essentially I am trying to only show products with a specific meta value such as:

case 'title_bulk' :
$args['orderby'] = 'meta_value';
$args['order'] = 'asc';
$args['meta_key'] = 'product_packaging';
$args['meta_value'] = 'Bulk';
$args['meta_compare'] = '=';
break;

replace $_SESSION with $_GET and magically, totally custom sorting starts working. found this at http://www.galalaly.me/index.php/2013/05/woocommerce-sort-by-custom-attributes/

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.