WooCommerce: Add product to cart with price override?

后端 未结 10 1601
轮回少年
轮回少年 2020-11-27 13:53
$replace_order = new WC_Cart();
$replace_order->empty_cart( true );
$replace_order->add_to_cart( \"256\", \"1\");

The above code add product

10条回答
  •  臣服心动
    2020-11-27 14:23

    You need to introduce an if statement for checking product id, in above code:

    add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
    
    function add_custom_price( $cart_object ) {
        $custom_price = 10; // This will be your custome price  
        $target_product_id = 598;
        foreach ( $cart_object->cart_contents as $value ) {
            if ( $value['product_id'] == $target_product_id ) {
                $value['data']->price = $custom_price;
            }
            /*
            // If your target product is a variation
            if ( $value['variation_id'] == $target_product_id ) {
                $value['data']->price = $custom_price;
            }
            */
        }
    }
    

    Add this code anywhere and make sure that this code is always executable.

    After adding this code, when you'll call:

    global $woocommerce; 
    $woocommerce->cart->add_to_cart(598);
    

    Only this product will be added with overridden price, other products added to cart will be ignored for overriding prices.

    Hope this will be helpful.

提交回复
热议问题