在 WooCommerce 中对特定产品类别的购物车项目进行排序

Sort specific product category cart items at the end in WooCommerce

如何将已定义产品类别中的项目排序为购物车订单的末尾,例如,我希望属于产品类别 'bottle' 的所有产品都位于购物车订单的末尾.

我找到了这个按价格排序的代码,但我想按照上面的描述进行调整。

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() conditional WordPress function检查购物车项目是否属于产品类别(但需要为相关产品(项)设置定义的类别).

因此,以下代码将在末尾对购物车中属于指定类别的商品进行排序:

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 );
}

代码进入活动子主题(或活动主题)的 functions.php 文件。已测试并有效。