"Sort by SKU" Option in the Shop
Adds a "Sort by product code" choice to the shop's sorting dropdown, useful for trade catalogues where customers order by code.
Opens WPIDE on
Code
add_filter( 'woocommerce_catalog_orderby', function ( $options ) {
$options['sku'] = 'Sort by product code';
return $options;
} );
add_filter( 'woocommerce_get_catalog_ordering_args', function ( $args, $orderby ) {
if ( 'sku' === $orderby ) {
$args['orderby'] = 'meta_value title';
$args['order'] = 'ASC';
$args['meta_key'] = '_sku'; // phpcs:ignore WordPress.DB.SlowDBQuery
}
return $args;
}, 10, 2 );
Notes
Products without a SKU are listed last.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.