代码之家  ›  专栏  ›  技术社区  ›  developerme

如何在购物车中更改可变产品价格在Woomerce中删除删除特定产品表单购物车

  •  3
  • developerme  · 技术社区  · 6 年前

    我的站点我在购物车中添加了一个可变产品。当时,另一个可变产品也添加到购物车中,该产品是礼品产品。现在,我想将礼品可变产品价格更改为0。只有在条件满足购物车中提供礼品的产品时,它才能工作。此外,我想删除两个产品形式相同,点击产品提供礼品。下面我的代码是不适合我。

    add_action( 'woocommerce_before_calculate_totals', 'change_custom_price' );
    
    function change_custom_price( $cart_object ) {
        $custom_price = 0; // This will be your custome price  
        $gift_variation_id = 2046;
        foreach ( $cart_object->cart_contents as $value ) {
            if ( $value['variation_id'] == $gift_variation_id ) {
                $value['data']->price = $custom_price;
            }
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   Outsource WordPress    6 年前

    可根据此解决方案添加礼品- Buy one get one in woocommerce with out coupon code .

    您可以将以下内容添加到主题的“functions.php”中,以删除其他产品自动添加的礼品。

    function remove_gift_product($cart_item_key) {
        global $woocommerce;
        $cat_in_cart = false;
        $coupon_in_cart = false;
    
        $autocoupon = array( 123411 ); // variation ids of products that offers gifts
        $freecoupon =  array( 2046 ); // variation ids of products that are gift coupons
    
        foreach ( $woocommerce->cart->cart_contents as $key => $values ) {      
            if( in_array( $values['variation_id'], $autocoupon ) ) {  
                $cat_in_cart = true;                
            }       
        }
    
        if ( !$cat_in_cart ) {          
            foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item) {
                if ( in_array( $cart_item['variation_id'], $freecoupon )) {             
                    $woocommerce->cart->remove_cart_item($cart_item_key);
                }
            } 
        }
    }
    add_action( 'woocommerce_cart_item_removed', 'remove_gift_product' );
    

    如果您想降低礼品的价格,请添加此项。

    function add_discount_price( $cart_object ) {
        global $woocommerce;
        $cat_in_cart = false;
    
        $autocoupon = array( 123411 ); // variation ids of products that offers gifts
        $freecoupon =  array( 2046 ); // variation ids of products that are gift coupons
    
        foreach ( $woocommerce->cart->cart_contents as $key => $values ) {      
            if( in_array( $values['variation_id'], $autocoupon ) ) {  
                $cat_in_cart = true;                
            }       
        }
        if ( $cat_in_cart ) {
            $custom_price = 0; // This will be your custome price     
            foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item) {
                if ( in_array( $cart_item['variation_id'], $freecoupon )) {
                     $cart_item['data']->set_price($custom_price);
                }        
            }
        }
    }
    
    add_action( 'woocommerce_before_calculate_totals', 'add_discount_price' );