Sorting order items by SKU in Woocommerce(在 Woocommerce 中按 SKU 对订单项进行排序)
问题描述
我正在尝试在 Woocommerce 中通过电子邮件中的订单内的 sku 订购产品.
我对以下代码没有任何运气.
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 );
样本排序结果:
- INFSTRAW I
- NFMUFFIN
- INFFLORES
- INFTAFOR
- INFTAPINK
- CTEPINK4
- CTECAKE4
- INFCHOCO
- UCUBTOMA
推荐答案
2020 年 7 月更新
方法如下:
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 对订单项进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Woocommerce 中按 SKU 对订单项进行排序


基础教程推荐
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01