WooCommerce product archives support several ordering methods by default, including sorting by price, date, product name, and so on. Sometimes those built-in options do not fully match what we need. In those cases, we may want to add custom ordering methods so users can find products more easily and get a better browsing experience.
WooCommerce uses WordPress post meta as the basis for sorting, so if we want to add a custom ordering option, we first need a post meta field that can be used for sorting. For example, suppose we have already added a “likes” feature to WooCommerce, and the like count is stored in WordPress post meta with the meta key like.
Add a custom sorting option to the product list dropdown
Using the following code, we can add “Sort by popularity” to the WooCommerce product archive ordering dropdown.
add_filter('woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby');
// Add a new option to the $sortby parameter.
function custom_woocommerce_catalog_orderby($sortby) {
$sortby['like'] = "Sort by popularity";
return $sortby;
}
At this point, we have only added the custom option to the sorting dropdown. Choosing it still does nothing, because the actual sorting data has not been connected yet.
Add the custom field data used for sorting to the ordering logic
add_filter('woocommerce_get_catalog_ordering_args', 'custom_catalog_ordering_args');
function custom_catalog_ordering_args($args) {
global $wp_query;
// Get the ordering parameter.
if ($_GET['orderby'] == "like") {
$args['meta_key'] = 'like';
$args['orderby'] = 'meta_value';
$args['order'] = "ASC";
}
return $args;
}
Once the code above has been added, selecting “Sort by popularity” will make products sort according to the number of likes they have received, from high to low. Of course, you can also add other ordering methods based on your own needs.
