更改购物车中的WooCommerce优惠券折扣金额

时间:2020-07-14 16:41:41

标签: php wordpress woocommerce cart coupon

我在做什么: 我正在创建基于优惠券的促销。优惠券将打折购物车中属于特定产品类别的最昂贵商品的10%。

问题: 下面的代码成功检查购物车中是否包含特定类别的产品,并从该阵列中获得最昂贵产品价格的10%用作折扣。但是,我无法在购物车中更改优惠券折扣金额。

代码:

function change_coupon_price_for_promo( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ){
        return;
    }
    
    // coupon code
    $coupon_name = 'MYCOUPONNAME'; 
    
    // if coupon is applied to cart...
    if( $cart->has_discount( $coupon_name ) ) {
        
        // Form array of products from the cart that belong to the specified category
        $specProduct = array(); // array of specific products in cart
        foreach ( $cart->get_cart() as $key => $cart_item ) {
            $cart_item_id = $cart_item['product_id'];
            $terms = wp_get_post_terms( $cart_item_id, 'product_cat' );
            foreach ( $terms as $term ){
                // gets product cat id
                $product_cat_id = $term->term_id;
                // gets an array of all parent category levels
                $product_parent_categories_all_hierachy = get_ancestors( $product_cat_id, 'product_cat' );      
                // This cuts the array and extracts the last set in the array
                $last_parent_cat = array_slice($product_parent_categories_all_hierachy, -1, 1, true);
                if(in_array(3831, $last_parent_cat)){
                    $specProduct[$key] = $cart_item_id;
                    break;
                }
            }
        }
        
        //if there are items from the specific category in the cart
        if(!empty($specProduct)){
            $specPriceArray = array(); // array of specific product prices in cart
            foreach ($specProduct as $key => $specItem) {
                $thisProd = wc_get_product($specItem);
                $thisPrice = $thisProd->get_price();
                $specPriceArray[$key] = $thisPrice;
            }
            
            // most expensive specific product price
            $highestSpec = max($specPriceArray);
            // discount of most expensive item
            $finalDiscount = $highestSpec * .1;
            
            // print_r($specProduct); GOOD
            // print_r($specPriceArray); GOOD
            // echo $highestSpec; GOOD
            // echo $finalDiscount; GOOD

            /***** APPLY COUPON CHANGE HERE<-------HOW??? *****/
            $cart->discount_total = $finalDiscount;
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'change_coupon_price_for_promo', 10, 1 ); 

我要问的是

右括号前的代码的最后一行...

$ cart-> discount_total = $ finalDiscount;

是我用来更改购物车中优惠券折扣的方式。没用我该怎么做? TY。

编辑: 我应该注意,要添加的优惠券设置为“固定购物车折扣”,汇率为0,因此将其作为订单项添加到订单中。这样,用户可以在购物车/结帐单行中看到优惠券代码的折扣。

1 个答案:

答案 0 :(得分:0)

您可以使用函数set_price。 您可以在代码中调用它,例如:

$cart_item['data']->set_price('New price here')

在循环购物车物品的foreach中使用此功能