本文介紹了在 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 對訂單項進行排序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!