1
votes

I am trying to set the cart total to £10, when there are 4 items in the cart AND none of the items are from the 'christmas' category.

e.g.

  • 4 items in cart, but 4 from christmas category. Ignore rule and follow per item pricing.
  • 4 items in cart, but 4 from non-christmas category. Set cart price to £10.
  • 4 items in cart, but 2 from christmas category. Ignore rule and follow per item pricing.

I have written code which currently works to set any 4 cart tems to £10:

add_filter( 'woocommerce_calculated_total', 'calculated_total', 10, 2 );
function calculated_total( $total, $cart ) {
    $taster_item_count = 4;
    if ( $cart->cart_contents_count == $taster_item_count ) {
        return 10;
    }
    return $total;
}

However, when I try to add in the category conditional, it does not follow the rule?:

    add_filter( 'woocommerce_calculated_total', 'calculated_total', 10, 2 );

// check each cart item for  category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

    $product = $cart_item['data'];

    // ONLY EXECUTE BELOW FUNCTION IF DOESN'T CONTAIN CHRISTMAS CATEGORY
    if ( !has_term( 'christmas', 'product_cat', $product->id ) ) {

function calculated_total( $total, $cart ) {
    $taster_item_count = 4;
    if ( $cart->cart_contents_count == $taster_item_count ) {
        return 10;
    }
    return $total;
}
    }
}
1

1 Answers

1
votes

Updated: There are mistakes in your code, try this instead:

add_filter( 'woocommerce_calculated_total', 'calculated_total', 10, 2 );
function calculated_total( $total, $cart ) {
    $taster_count = 4;
    $item_count   = $cart->get_cart_contents_count();
    $chistm_count = 0;

    foreach ( $cart->get_cart() as $cart_item ) {
        if ( ! has_term( 'christmas', 'product_cat', $cart_item['product_id'] ) ) {
            $chistm_count += $cart_item['quantity'];
        }
    }
    if( $taster_count == $item_count && $chistm_count == $taster_count ) {
        $total = 10;
    }
    return $total;
}

It should better work.