問題描述
如何將定義的產(chǎn)品類別中的項(xiàng)目排序到購(gòu)物車訂單的末尾,例如,我希望屬于產(chǎn)品類別瓶子"的所有產(chǎn)品都位于購(gòu)物車訂單的末尾.
How to sort items from a defined product category to be at the end of a cart order, for example I want all products that belong to a product category 'bottle' to be at the end of the cart order.
我發(fā)現(xiàn)此代碼按價(jià)格排序,但希望按照上述方式進(jìn)行調(diào)整.
I have found this code that sorts by price, but would like to adjust to as described above.
add_action( 'woocommerce_cart_loaded_from_session', 'prefix_cart_order_prod_cat' );
function prefix_cart_order_prod_cat() {
$products_in_cart = array();
// Assign each product's price to its cart item key (to be used again later)
foreach ( WC()->cart->cart_contents as $key => $item ) {
$product = wc_get_product( $item['product_id'] );
$products_in_cart[ $key ] = $product->get_price();
}
// SORTING - use one or the other two following lines:
//asort( $products_in_cart ); // sort low to high
arsort( $products_in_cart ); // sort high to low
// Put sorted items back in cart
$cart_contents = array();
foreach ( $products_in_cart as $cart_key => $price ) {
$cart_contents[ $cart_key ] = WC()->cart->cart_contents[ $cart_key ];
}
WC()->cart->cart_contents = $cart_contents;
}
推薦答案
您可以使用 has_term()
WordPress 條件函數(shù) 用于檢查購(gòu)物車項(xiàng)目是否屬于產(chǎn)品類別(但需要為相關(guān)產(chǎn)品(項(xiàng)目)設(shè)置定義的類別).
You can use has_term()
conditional WordPress function to check if cart items belongs to a product category (but the defined category(ies) need to be set for the related products (items)).
因此,以下代碼將對(duì)購(gòu)物車中的商品與屬于指定類別的商品進(jìn)行排序:
So the following code will sort cart items with items belonging to specified category(ies) at the end:
add_action( 'woocommerce_cart_loaded_from_session', 'product_category_cart_items_sorted_end' );
function product_category_cart_items_sorted_end() {
$category_terms = __('T-shirts'); // Here set your category terms (can be names, slugs or Ids)
$items_in_category = $other_items = array(); // Initizlizing
// Assign each item in a different array depending if it belongs to defined category terms or not
foreach ( WC()->cart->cart_contents as $key => $item ) {
if( has_term( $category_terms, 'product_cat', $item['product_id'] ) ) {
$items_in_category[ $key ] = $item;
} else {
$other_items[ $key ] = $item;
}
}
// Set back merged items arrays with the items that belongs to a category at the end
WC()->cart->cart_contents = array_merge( $other_items, $items_in_category );
}
代碼位于活動(dòng)子主題(或活動(dòng)主題)的functions.php 文件中.經(jīng)測(cè)試有效.
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
這篇關(guān)于在 WooCommerce 的最后對(duì)特定產(chǎn)品類別的購(gòu)物車項(xiàng)目進(jìn)行排序的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!