基于产品类别和 Woocommerce 中的项目计数的购物车总数

Cart total based on product category and items count in Woocommerce

我试图将购物车总价设置为 10 英镑,当时购物车中有 4 件商品并且 none 件商品来自 'christmas' 类别。

例如

我编写了代码,目前可以将任意 4 个购物车商品设置为 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;
}

但是,当我尝试在类别条件中添加时,它不符合规则?:

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

更新:你的代码有错误,试试这个:

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

它应该更好用。