我使用以下代码片段按类别对购物车进行排序:
//order in cart
function woocommerce_before_cart_contents(){
global $woocommerce;
$cat_wisw_pros = array();
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {
$product_id = $cart_item['product_id'];
$cat_ids = wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'ids' ) );
foreach ( $cat_ids as $id ) {
$cat_wisw_pros[$id][$cart_item_key] = $cart_item;
}
}
ksort( $cat_wisw_pros ); // Cat ID wise sort
$grouped_cart_items = array();
foreach ( $cat_wisw_pros as $cat_id => $cart_items ) {
foreach ( $cart_items as $cart_item_key => $cart_item ) {
if( !array_key_exists( $cart_item_key, $grouped_cart_items ) )
$grouped_cart_items[$cart_item_key] = $cart_item;
}
}
$woocommerce->cart->cart_contents = $grouped_cart_items;
}
add_action( 'woocommerce_before_cart_contents', 'woocommerce_before_cart_contents' );
效果非常好,如图所示:
红框: 产品类别“Basic Products-GNC-Verkauf”是第一个,然后是“Werbematerial/Luxusproben”。
但是我一付款,却没有排序。所以问题是,发票上的排序顺序消失了。但我需要客户可以看到订单已排序。
如何申请需要排序的订单?
离开购物车页面时不再应用自定义排序顺序,因为您正在使用
woocommerce_before_cart_contents
钩子。
您可以将其替换为
woocommerce_cart_loaded_from_session
挂钩,因此自定义排序顺序也会应用于订单接收页面。此外,我对您现有的代码做了一些调整:
global $woocommerce
,因为 $cart
已传递给回调函数wp_get_post_terms()
替换为 get_category_ids()
所以你得到:
// Order in cart and order review page
function action_woocommerce_cart_loaded_from_session( $cart ) {
// Initialize
$cat_cart_items = array();
$grouped_cart_items = array();
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Get the product categories ID for this item
$cat_ids = $cart_item['data']->get_category_ids();
// Push to array
foreach ( $cat_ids as $id ) {
$cat_cart_items[$id][$cart_item_key] = $cart_item;
}
}
// Sort an array by key in ascending order
ksort( $cat_cart_items );
// Loop through cat cart items
foreach ( $cat_cart_items as $cart_items ) {
// Loop through cart items
foreach ( $cart_items as $cart_item_key => $cart_item ) {
// Checks an array for a specified key and if the key does not exist
if ( ! array_key_exists( $cart_item_key, $grouped_cart_items ) ) {
// Push to array
$grouped_cart_items[$cart_item_key] = $cart_item;
}
}
}
// Cart contents
$cart->cart_contents = $grouped_cart_items;
}
add_action( 'woocommerce_cart_loaded_from_session', 'action_woocommerce_cart_loaded_from_session', 10, 1 );
如何按价格对它们进行排序?我尝试过使用 get_price() 但它返回空值