Set custom price for woocommerce cart before calculate

Fact Check new search feature by Google
April 11, 2017
Inception Cab Fare – Demo
April 17, 2017
Show all

Set custom price for woocommerce cart before calculate

Woocommerce is the most customizable eCommerce platform for building your online business. Here is an example to see it in action.

Custom Price for All product

You can add Custom Price for all products via’woocommerce_before_calculate_totals’ action.
See Example below:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );

function add_custom_price( $cart_object ) {

    $custom_price = 100; //Custom price you want to add
    
    $value['data']->set_price($custom_price);// as you can not set price directly now
    
}

Custom Price for Single product

You can add Custom Price for any product based on product_id via’woocommerce_before_calculate_totals’ action.
See Example below:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );

function add_custom_price( $cart_object ) {

    global $woocommerce;
    
    $custom_price = 10 ; // This will be your custome price
    $target_product_id = 1;//some product id
    
    foreach ( $cart_object->cart_contents as $key => $value ) {
    
        if ( $value['product_id'] == $target_product_id ) {
            $value['data']->set_price($custom_price);
        }
        
    }
}

 

Leave a Reply