Change price of product in WooCommerce cart and checkout

Viewed 8566

I'm creating a WooCommerce add-on to customize the product, based on selected options by the visitor and custom price is calculated and stored into session table also.
I am able to get that value in cart page also.

My problem:
I would like to change the default price of the product and replace it with new calculated value in the WooCommerce process as cart, checkout, payment, mail notifications, order...

Any advice please?

Thanks

2 Answers
function save_subscription_wrap_data( $cart_item_data, $product_id ) {
    $include_as_a_addon_subscription = get_field('include_as_a_addon_subscription',$product_id);
    $subscricption_product_data = get_field('subscricption_product',$product_id);
    $current_user  = is_user_logged_in() ? wp_get_current_user() : null;
    $subscriptions = wcs_get_users_subscriptions( $current_user->ID );
    if($include_as_a_addon_subscription == "yes")
    {
        foreach ( $subscriptions as $subscription_id =>  $subscription ) {
            $subscription_status = $subscription->get_status();
        }
        if($subscription_status == 'active')
        {
            $cart_item_data[ "subscribe_product" ] = "YES";  
        }
    }
    return $cart_item_data;
     
}
add_filter( 'woocommerce_add_cart_item_data', 'save_subscription_wrap_data', 99, 2 );

function render_meta_on_cart_and_checkout1( $cart_data, $cart_item = null ) {
   $meta_items = array();
    
    if( !empty( $cart_data ) ) {
        $meta_items = $cart_data;
    }
    if( isset( $cart_item["subscribe_product"] ) ) {
        $meta_items[] = array( "name" => "Product Type", "value" => "Package Addon" );
    }
    return $meta_items;
}
add_filter( 'woocommerce_get_item_data', 'render_meta_on_cart_and_checkout1', 100, 2 );

function calculate_gift_wrap_fee( $cart_object ) {
    if( !WC()->session->__isset( "reload_checkout" )) {
        
        $additionalPrice = 100;
        foreach ( WC()->cart->get_cart() as $key => $value ) {
            if( isset( $value["subscribe_product"] ) ) {                
                if( method_exists( $value['data'], "set_price" ) ) {
                                        
                    $orgPrice = floatval( $value['data']->get_price() );
                    //$value['data']->set_price( $orgPrice + $additionalPrice );
                    $value['data']->set_price(0);
                } else {
                        
                    $orgPrice = floatval( $value['data']->price );
                    //$value['data']->price = ( $orgPrice + $additionalPrice );
                    $value['data']->price = (0);
                }           
            }
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'calculate_gift_wrap_fee', 99 );
Related