How to add sort by sku in Woocommerce shop page ordering dropdown ?

To add a new custom default ordering catalog option in WooCommerce for ordering by SKU, you'll need to use filters and functions provided by WooCommerce. Here's how you can do it:

Open your theme's functions.php file or create a custom plugin.

Use the woocommerce_catalog_orderby filter hook to add a new sorting option to the catalog order dropdown. Add the following code to your theme's functions.php file or your custom plugin:


function add_custom_orderby_option($options) {

    $options['sku'] = __('Sort by SKU', 'woocommerce');

    return $options;

}

add_filter('woocommerce_catalog_orderby', 'add_custom_orderby_option');


Use the woocommerce_get_catalog_ordering_args filter hook to modify the default ordering arguments when the custom SKU option is selected. Add the following code to your theme's functions.php file or your custom plugin:


function custom_orderby_sku($args) {

    if (isset($_GET['orderby']) && $_GET['orderby'] === 'sku') {

        $args['orderby'] = 'meta_value';

        $args['order'] = 'ASC';

        $args['meta_key'] = '_sku';

    }

    return $args;

}

add_filter('woocommerce_get_catalog_ordering_args', 'custom_orderby_sku');


Save the changes and test it on your WooCommerce website. You should now see the "Sort by SKU" option in the catalog order dropdown, and when selected, the products will be sorted by SKU in ascending order.




Note: The SKU value must be set for each product for this sorting option to work correctly. If any products do not have an SKU assigned, they may not be ordered as expected.

Post a Comment

0 Comments