Add a new custom default ordering catalog option in Woocommerce

喜夏-厌秋 提交于 2019-12-01 12:51:20

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 function.php file of your active child theme (or active theme). Tested and works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!