在Woocommerce中按SKU对订单项进行排序 [英] Sorting order items by SKU in Woocommerce

查看:146
本文介绍了在Woocommerce中按SKU对订单项进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Woocommerce 中尝试通过电子邮件中的订单按sku订购产品.

I am trying to order the products by sku within an order in an email in Woocommerce.

我对以下代码没有任何帮助.

I have not had any luck with the following code.

有帮助吗?从现在开始谢谢!

Some help? Thanks since now!

add_filter( 'woocommerce_order_get_items', function( $items, $order ) {
    uasort( $items,
        function( $a, $b ) {
            return strnatcmp( $a['_sku'], $b['_sku'] );
        }
    );
    return $items;
}, 10, 2 );

样本排序结果:

  • INFSTRRAW I
  • NFMUFFIN
  • INFFLORES
  • INFTAFLOR
  • INFTAPINK
  • CTEPINK4
  • CTECAKE4
  • INFCHOCO
  • UCUBTOMA

推荐答案

已于2020年7月更新

这是执行此操作的方法:

Here is the way to do it:

add_filter( 'woocommerce_order_get_items', 'filter_order_get_items_by_sku', 10, 3 );
function filter_order_get_items_by_sku( $items, $order, $types ) {
    if( count($items) > 1 ) {
        $item_skus = $sorted_items = array();

        // Loop through order line items
        foreach( $items as $items_id => $item ){
            // Check items type: for versions before Woocommerce 3.3
            if( $item->is_type('line_item') && method_exists( $item, 'get_product' ) ){
                $product = $item->get_product(); // Get the product Object
                if( is_a( $product, 'WC_Product' ) ) {
                    $item_skus[$product->get_sku()] = $items_id;
                }
            }
        }

        // Only for line items when our sku array is not empty
        if( ! empty($item_skus) ) {
            // Sorting in ASC order based on SKUs;
            ksort($item_skus); // or use krsort() for DESC order

            // Loop through sorted $item_skus array
            foreach( $item_skus as $sku => $item_id ){
                // Set items in the correct order
                $sorted_items[$item_id] = $items[$item_id];
            }
            $items = $sorted_items;
        }
    }
    return $items;
}

代码进入您的活动子主题(或活动主题)的function.php文件中.经过测试,可以正常工作.

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

这将在后端和前端订单以及电子邮件通知中按sku订单ASC对项目进行排序

This will sort items by sku order ASC on backend and frontend orders and in email notifications


在将订单保存到数据库之前对订单进行排序后,也可以对项目进行排序.


Also sorting items once the order is placed before data is saved to the database, could be a better way to do it.

这篇关于在Woocommerce中按SKU对订单项进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆