How to dynamically change price in woocommerce without any plugin ?


To dynamically change the price in WooCommerce, you can utilize hooks and filters provided by WooCommerce. Here's an example of how you can achieve it:

Open your theme's functions.php file or create a custom plugin.

Use the woocommerce_before_calculate_totals filter hook to modify the price dynamically. Add the following code to your theme's functions.php file or your custom plugin:


add_action( 'woocommerce_before_calculate_totals', 'wcSetPriceProductPrice', 10, 1 );

if (!function_exists('wcSetPriceProductPrice')) 

{

function wcSetPriceProductPrice( $cart ) 

{

foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) 

{

if( isset( $cart_item['wc_new_price'] ) ) 

{

$price = $cart_item['wc_new_price'];

$cart_item['data']->set_price($price);

}

}

}

}


In this above example they have get the price from cart item 'wc_new_price', using the below code you can set the custom price in cart. To set the custom data in cart you can use "woocommerce_add_cart_item_data" filter.


add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 10, 3 );

if (!function_exists('add_cart_item_data')) 

{

function add_cart_item_data( $cart_item_data, $product_id, $variation_id ) 

{

if (isset($_REQUEST['wc_custom_price']) && !empty($_REQUEST['wc_custom_price']))

{

$cart_item_data['wc_new_price'] = $_REQUEST['wc_custom_price'];

}

return $cart_item_data;

}

}

Save the changes and test it on your WooCommerce website. The prices of the products should now be dynamically changed based on your custom logic.

Thanks!

Post a Comment

0 Comments