首页 > 解决方案 > 基于 Woocommerce 中的产品类别和项目计数的购物车总数

问题描述

我正在尝试将购物车总额设置为 10 英镑,当购物车中有 4 件商品并且没有一件商品属于“圣诞节”类别时。

例如

我已经编写了代码,目前可以将任何 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;
}
    }
}

标签: phpwordpresswoocommercecarthook-woocommerce

解决方案


更新:您的代码中有错误,请尝试以下操作:

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

它应该更好地工作。


推荐阅读