Sort WooCommerce Products by SKU Numeric (1.2.3.4.5.6…)

末鹿安然 提交于 2021-01-29 01:56:44

问题


In WooCommerce Version 4.2.2 on admin products list, when I try to sort products by SKU (column), the result is: 1 10 100 101 102 103 104 ...
InsteadI would like it to be in natural order like: 1 2 3 4 5 ... 9 10 11 ... 99 ... 100 101 ...

The same thing happens when I use WooCommerce Product Search (Version 2.21.0).

Trying to understand what is happening I noticed that if I do a search in the admin panel for products it returns too many results and this does not happen to all products, some work and it only brings me 1 single product, others bring more.

I tried to reinstall all Wordpress, WooCommerce and WooCommerce product search, without any change. I tested other search plugins with the same results.

Any help please?


回答1:


The rule in StackOverFlow is one question at the time… So I am answering for admin products list.

The following hooked function will allow to sort products by numerical skus in a natural sorting order altering the ORDER BY in the related SQL query using ABS():

add_filter( 'posts_clauses', 'admin_products_list_orderby_sku_as_int', 999, 1 );
function admin_products_list_orderby_sku_as_int( $posts_clauses ){
    global $pagenow, $typenow, $wp_query;

    $query_vars = $wp_query->query_vars;

    if ( $pagenow == 'edit.php' && 'product' === $typenow && isset( $_GET['post_type'] )
    && isset( $query_vars['orderby'] ) && 'sku' === $query_vars['orderby'] ) {
        $orderby   = strtolower( $query_vars['orderby'] );
        $order     = isset( $query_vars['order'] ) ? strtoupper( $query_vars['order'] ) : 'DESC';

        if ( 'DESC' === $order ) {
            $posts_clauses['orderby'] = ' ABS( wc_product_meta_lookup.sku ) DESC, wc_product_meta_lookup.sku DESC, wc_product_meta_lookup.product_id DESC ';
        } else {
            $posts_clauses['orderby'] = ' ABS( wc_product_meta_lookup.sku ) ASC, wc_product_meta_lookup.sku ASC, wc_product_meta_lookup.product_id ASC ';
        }
    }
    return $posts_clauses;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

See: SQL ORDER chars numerically



来源:https://stackoverflow.com/questions/62588792/sort-woocommerce-products-by-sku-numeric-1-2-3-4-5-6

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