WooCommerce: Add product to cart with price override?

后端 未结 10 1449
轮回少年
轮回少年 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.

    0 讨论(0)
  • 2020-11-27 14:23

    For eveeryone that got here from Google. The above is now deprecated as i found out updating to WooCommerce 3.0.1.

    Instead of the above you now need to use set_price instead of price

    Here is an example:

    add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
    function add_custom_price( $cart_object ) {
        $custom_price = 10; // This will be your custome price  
        foreach ( $cart_object->cart_contents as $key => $value ) {
            $value['data']->set_price = $custom_price;
        }
    }
    

    I hope this helps people in the future :)

    0 讨论(0)
  • 2020-11-27 14:27

    For the Wordpress and Woocommerce latest version,Please use like this

    add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
    
    function add_custom_price( $cart_object ) {
        foreach ( $cart_object->cart_contents as $key => $value ) {
            $custom_price = 5;
            $value['data']->set_price($custom_price); 
        }
    }
    
    0 讨论(0)
  • 2020-11-27 14:27

    You can use the following

    add_filter( 'woocommerce_cart_item_price', 'kd_custom_price_message' );
    
    function kd_custom_price_message( $price ) {
    
            $textafter = ' USD'; 
            return $price . $textafter;
    }
    
    0 讨论(0)
提交回复
热议问题