Add a new custom default ordering catalog option in Woocommerce

后端 未结 1 1866
太阳男子
太阳男子 2020-12-20 05:25

I am trying to get the default order of Woocommerce to be order by SKU. I have changed the order in the woocommerce settings and added SKU like this:

functi         


        
相关标签:
1条回答
  • 2020-12-20 05:53

    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........)

    0 讨论(0)
提交回复
热议问题