Sort WooCommerce products from product category to be last in cart order

From a selected WooCommerce product category sort products to be at the end of a carts order.

add_action( 'woocommerce_cart_loaded_from_session', 'product_category_cart_items_sorted_end' );
/**
 * WooCommerce - sort some Prod Cat items to be last order in cart
 * @link https://stackoverflow.com/questions/65800801/sort-specific-product-category-cart-items-at-the-end-in-woocommerce
 */
function product_category_cart_items_sorted_end() {
    $category_terms    = __('box'); // Here set your category terms (can be names, slugs or Ids)
    $items_in_category = $other_items = array(); // Initialising

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

Above example uses ‘box’ as a product category, to re-arrange the order swap the arrays in array_merge.

WC()->cart->cart_contents = array_merge( $items_in_category, $other_items );

Leave all Comment