Updated (Dec 2018)
You are not using the right hooks in the right way to get default ordering catalog by sku. There is also some missing needed additional code:
add_filter( 'woocommerce_get_catalog_ordering_args', 'enable_catalog_ordering_by_sku' );
function enable_catalog_ordering_by_sku( $args ) {
if ( isset( $_GET['orderby'] ) ) {
if ( 'sku' == $_GET['orderby'] ) {
return array(
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_key' => '_sku',
);
}
// Make a clone of "menu_order" (default option)
elseif ( 'natural_order' == $_GET['orderby'] ) {
return array( 'orderby' => 'menu_order title', 'order' => 'ASC' );
}
}
return $args;
}
add_filter( 'woocommerce_catalog_orderby', 'add_catalog_orderby_by_sku' );
function add_catalog_orderby_by_sku( $orderby_options ) {
// Insert "Sort by product reference (sku)" and the clone of "menu_order"
return array(
'sku' => __("Sort by product reference (sku)", "woocommerce"),
'natural_order' => __("Sort by natural shop order", "woocommerce"), // <== To be renamed at your convenience
) + $orderby_options ;
}
add_filter( 'woocommerce_default_catalog_orderby', 'default_catalog_orderby_sku' );
function default_catalog_orderby_sku( $default_orderby ) {
return 'sku';
}
add_action( 'woocommerce_product_query', 'product_query_by_sku' );
function product_query_by_sku( $q ) {
if ( ! isset( $_GET['orderby'] ) && ! is_admin() ) {
$q->set( 'orderby', 'meta_value_num' );
$q->set( 'order', 'ASC' );
$q->set( 'meta_key', '_sku');
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Related: Sort WooCommerce Products by SKU Numeric (1.2.3.4.5.6........)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…