Scale your business with our modular plugins.
Home » Blog » How to Update Product Price Programmatically in WooCommerce

How to Update Product Price Programmatically in WooCommerce

How to update product price programmatically in WooCommerce
October 27, 2025||By Sebastian Rossi

Do you want to learn how to update the product price programmatically in WooCommerce? In this guide, we’ll show you how to change prices in WooCommerce without using plugins or installing extra tools.

If you use them smartly, discounts can help you improve your conversion rates and increase your sales. There are several ways to implement discounts on your e-commerce store. For example, you can apply WooCommerce coupons programmatically.

However, you can also update the product price without using coupons. For example, you could give an exclusive discount to users who subscribe to your newsletter or who have spent more than $100 in your store.

In this guide, you’ll learn to change the price when customers add a product to the cart without using coupons and by accessing the WooCommerce cart object directly. We’ll look at some examples and apply some logic when updating the price.

The goal is that you understand the logic so you can customize the scripts and apply them to your store.

When Should You Update Product Price Programmatically?

There are several situations where updating product prices manually just isn’t efficient. That’s when you should consider using code to change product pricing. Here are the most common scenarios where it makes sense to update WooCommerce product prices programmatically:

  • Bulk Price Updates: Manually changing prices can be time-consuming when managing hundreds or thousands of products. A programmatic approach lets you update prices quickly and accurately in bulk.
  • Dynamic Pricing Rules: When your pricing depends on real-time data—like currency rates, competitor prices, or stock levels—you can use custom scripts to change WooCommerce product prices automatically.
  • Sales and Promotions: Want to run flash sales or apply discounts automatically on certain days? You can programmatically schedule a WooCommerce product price update using cron jobs or hooks.
  • External Data Integration: If your store pulls pricing from an external system or API, you’ll need a reliable way to update product prices automatically in WooCommerce.
  • Multi-Store or Multi-Vendor Setup: If prices need to be synced across multiple stores or vendor portals, the code ensures consistency and reduces manual effort.

By automating these processes, you can eliminate repetitive tasks and reduce the risk of human error, making your WooCommerce store more efficient and scalable.

How to Update the Product Price Programmatically in WooCommerce

In this section, you’ll learn how to update the product price programmatically in WooCommerce. We’ll look at different examples to give you some ideas of what you can do in your store.

  1. Update product price when a checkbox is selected
    1. Add the checkbox input field to the products page
    2. Update the price when a user adds a product to the cart
    3. Recalculate the total price of the cart
  2. Edit the product price based on user roles
  3. Update the product price based on the product taxonomy

Remember that we’ll use several WooCommerce hooks, so it’s a good idea to check out this guide if you’re unfamiliar with them.

Before we start…

Before we start, as we’ll modify some core files, we recommend you install a child theme on your site. If you don’t have a child theme and you don’t know how to install it, check out our guide to creating a child theme or our list of the best child theme plugins.

NOTE: To apply these scripts, copy and paste them into the functions.php child theme file. However, remember that they’re intended solely for didactic purposes, so customize them before taking them to production.

1) Update Product Price When a Checkbox is Selected

How to update product price programmatically in WooCommerce

In the following sample script, we’ll add a checkbox input in the cart form on the product page. This way, we can apply custom logic and dynamically update the price of any product that customers add to the cart only when the checkbox is selected.

1.1 Add the Checkbox Input Field to the Products Page

Before we update the WooCommerce product price programmatically, let’s add the checkbox to the products page. To do that, copy and paste the following script:

add_action('woocommerce_after_add_to_cart_button', 'add_check_box_to_product_page', 30 );
function add_check_box_to_product_page(){ ?>     
       <div style="margin-top:20px">           
<label for="extra_pack"> <?php _e( 'Extra packaging', 'quadlayers' ); ?>
<input type="checkbox" name="extra_pack" value="extra_pack"> 
</label>
                    
</div>
     <?php
}

The woocommerce_after_add_to_cart_button The hook allows us to print the checkbox right after the button, as shown in the image above.

1.2 Update the price when the user adds a product to the cart

Another interesting option is to update prices when customers add products to their carts dynamically. So, in this case, to update the price programmatically in WooCommerce, paste this script right after the previous one.

add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 10, 3 );
 
function add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
     // get product id & price
    $product = wc_get_product( $product_id );
    $price = $product->get_price();
    // extra pack checkbox
    if( ! empty( $_POST['extra_pack'] ) ) {
       
        $cart_item_data['new_price'] = $price + 15;
    }
return $cart_item_data;
}

woocommerce_add_cart_item_data is the WooCommerce hook that will allow us to edit the price of the current product. Additionally, the if() conditional checks whether the checkbox is selected, and if it is, updates the price in the following line. Now, let’s break down the code to understand better what each part does.

  • extra_pack is the name of the checkbox we’ve created in the previous step
  • $price is the current product price. We can modify it as we want, with some conditions
  • $cart_item_data['new_price'] = $price + 15; is how we increase the price by $15 is when the if() condition is true, which is when the user selects the extra packaging checkbox. By adjusting the code, you can increase or decrease the price by any amount you want.

1.3 Recalculate the Total Price of the Cart

Since we can call the woocommerce_add_cart_item_data when loading the cart several times, we need to recalculate the totals and subtotals of the cart to avoid undesired results such as prices being updated multiple times or every time a user adds a product. To update the product, paste the following code after the previous two ones:

add_action( 'woocommerce_before_calculate_totals', 'before_calculate_totals', 10, 1 );
 
function before_calculate_totals( $cart_obj ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
// Iterate through each cart item
foreach( $cart_obj->get_cart() as $key=>$value ) {
if( isset( $value['new_price'] ) ) {
$price = $value['new_price'];
$value['data']->set_price( ( $price ) );
}
}
}

This function ensures we update the price only when a product matches our conditional logic (i.e., when the user selects the extra packaging checkbox). This way, we prevent all potential errors when calculating the cart’s total price. Update product price programmatically in WooCommerce - Extra fee

Product price increases by $15

If everything goes well and the cart meets the conditions we set, our function will add an extra $15 charge to the original price when the user selects the checkbox on the product page before clicking the Add to cart button.

To reduce cart abandonment and improve the buying experience, always display the new price before customers add products to their carts. Otherwise, they’ll only see the final price on the checkout page.

2. Edit the Product Price Based on User Roles

Similarly, we can programmatically update the WooCommerce product price based on user roles. For example, you could give subscribed or registered users an exclusive discount. To do that, copy and paste the following script:

function add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
    // get product id & price
   $product = wc_get_product( $product_id );
   $price = $product->get_price();
   if(// Is logged in && is customer role
       is_user_logged_in()==true&& wc_current_user_has_role( 'customer' )){
       
        $cart_item_data['new_price'] = $price * 0.8;
   }
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 10, 3 );

As you can see, the only difference between this script and the previous one in point 1.2 is the if() logic operator. Here, we check whether the user is logged in and has a customer role, which we assign to registered users who have purchased from our store before.

When a shopper meets that condition, we multiply the product price by 0.8, giving them a 20% discount. Of course, you can edit and change other users’ roles, such as Subscriber, Editor, or any other roles you have registered on your website.

Note that to work correctly, you must use the 'before_calculate_totals' function and its hook to recalculate the cart totals. So, recalculate the cart script’s total price from step 1.3.

3. Update Product Price Based on Product Taxonomy

Finally, in WooCommerce, we can also dynamically update the product price programmatically based on product taxonomies. To do that, let’s look at the following script.

add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 10, 3 );
 
function add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
     // get product id & price
    $product = wc_get_product( $product_id );
    $price = $product->get_price();
    $terms = get_the_terms( $product_id, 'product_cat' );
    // Category match ! apply discount
    if($terms[0]->name=='Posters'){                    
        $cart_item_data['new_price'] = $price + 20;
     }   
return $cart_item_data;
 
}

In this example, we are getting the category of the product that has been added to the cart using the get_the_terms() WordPress’s built-in function. In the following line, we apply our condition to retrieve the category of the product using $terms[0]->name. This way, if the product belongs to the category Posters, we increase the price by $20.

This is a sample script that you can use as a base and edit to change the taxonomy and the amount you want to add or deduct from the price.

Finally, remember to use the 'before_calculate_totals' function and its corresponding hook as we did in step 1.3.


As you can see, the know-how to use conditional statements and WordPress/WooCommerce functions provides a highly flexible way to update product prices programmatically. These are just a few examples to give you ideas of what’s possible.

However, there’s a lot more you can do to unleash your creativity and find new ways to lower your product prices. For example, you can apply discounts based on specific product IDs, the URL users came from, users’ location or ID, and so on. The possibilities are endless —play around with the script and find the best solutions for your store.

FINAL NOTES

  • These sample scripts in points 1, 2, and 3 will not work together. You will need to refine your logic into a single one if you want to apply multiple functions at the same time.
  • You may need to include additional validation functions for more complex conditional logic.
  • Always apply a recalculation function, as seen in point 1.3, when working with the WooCommerce cart object.
  • These are sample scripts and are intended for didactic purposes only. Please adjust them before taking them into production.

Pro Tips for Safe Price Updates

Here are some pro tips you should keep in mind:

  • Always back up your site before running any code that updates product prices. This ensures you can restore your data if something goes wrong.
  • Test your code in a staging environment first. Avoid making changes directly on your live WooCommerce store.
  • Use product IDs carefully. Double-check that you update the correct product or variation to prevent accidental price changes.
  • Include validation and error handling in your code to catch potential issues before they affect your live site.
  • Avoid bulk updates during peak traffic hours to minimize potential disruptions for customers browsing your store.
  • Log your changes. Maintain a log file or an admin notification system to track price modifications.
  • Keep your WooCommerce version updated. Compatibility with functions like woocommerce_update_product_price_programmatically or woocommerce_change_product_price_programmatically often depends on having the latest version.
  • Use WooCommerce hooks and functions properly to ensure updates align with WooCommerce’s best practices.
  • Avoid hardcoding values. If you update prices regularly, consider using variables or dynamic inputs based on specific criteria, such as stock levels or seasonal demand.

Common Mistakes to Avoid

  • Directly editing core WooCommerce files instead of using hooks or custom functions. This can break your site during updates.
  • Failing to sanitize or validate input values can lead to unexpected behavior or vulnerabilities.
  • Updating prices without checking product types can cause issues when working with variable or grouped products.
  • Running update scripts on every page load can slow down your site and overload your server.
  • Ignoring WooCommerce caching mechanisms, which can prevent new prices from showing immediately on the frontend.
  • Not using wp_update_post() or wc_delete_product_transients() When necessary, this might result in price changes not reflecting properly.
  • Applying the same price to all variations blindly, especially when each variation needs a unique price.
  • Forgetting to test edge cases like out-of-stock products, draft products, or those with set sale prices.

Plugins to Help You Update Product Prices in WooCommerce

If you need to use dedicated plugins to manage the price of your WooCommerce products, here are some recommendations.

1. Bulk Edit Products, Prices & Attributes for WooCommerce

Bulk Edit Products, Prices & Attributes for WooCommerce

This plugin is one of the easiest ways to update product prices in bulk without writing code. You can search, filter, and select products by category, attribute, or tag, then change their regular or sale prices with a single action.

It supports both fixed-price adjustments and percentage-based increases or decreases. The plugin’s spreadsheet-like interface makes it easy to preview changes before applying them, reducing errors.

You can also edit stock quantities, product titles, SKUs, and attributes simultaneously, making it a complete bulk management solution.

For larger stores with hundreds of products, this tool saves significant time compared to manual updates.

Features

  • Bulk edit prices, stock, categories, and attributes for thousands of products.
  • Supports simple, variable, and external product types.
  • Includes powerful filters to target specific products before editing.
  • Allows reverting recent edits with the undo option.
  • Compatible with custom fields and product metadata.

Pros

Cons

  • Premium-only plugin with no free version.
  • May take time to master for beginners.

2. Advanced Bulk Edit for WooCommerce

Advanced Bulk Edit for WooCommerce

Advanced Bulk Edit provides a flexible way to manage product prices in bulk. It offers a robust filtering system to target specific products and apply changes in a single step.

You can increase or decrease prices by a fixed amount or a percentage, update sale prices, or schedule future price changes.

The plugin also allows bulk editing of product descriptions, images, stock status, and categories. Its intuitive table-style interface helps you edit multiple products quickly and accurately.

Advanced Bulk Edit is perfect for store owners running frequent promotions and seasonal discounts, or for those who need to keep extensive inventories up to date.

Features

  • Edit over 40 WooCommerce product fields, including price, stock, and attributes.
  • Supports all product types like simple, variable, grouped, and external.
  • Includes advanced filters to target specific products easily.
  • Offers bulk operations, such as search-and-replace or increase-and-decrease values.
  • Works seamlessly with custom fields and third-party extensions.

Pros

  • Great for stores with extensive product catalogs.
  • Saves time and reduces manual editing errors.
  • Intuitive and straightforward interface.
  • Supports complex editing operations in bulk.

Cons

  • Premium-only plugin with no free version.
  • Slight learning curve for beginners.

3. WP All Import with WooCommerce Add-On

WP All Import

WP All Import is a robust tool for importing and updating WooCommerce product data using CSV or XML files. With its WooCommerce add-on, you can map product fields and update regular or sale prices in bulk directly from your spreadsheet.

This plugin is ideal for stores that manage inventory externally or receive product data from suppliers. You can set up automated imports on a schedule, ensuring your product prices remain accurate without manual updates.

WP All Import also supports updating product variations, stock levels, and custom fields, making it a complete bulk management solution.

Features

  • Imports all product types —simple, variable, and grouped —from CSV or XML files.
  • Offers a drag-and-drop interface for easy data mapping.
  • Supports bulk image imports and automatic gallery creation.
  • Enables scheduled imports to sync with supplier feeds.
  • Works seamlessly with custom fields, taxonomies, and multilingual plugins.

Pros

  • Highly flexible and supports complex product data.
  • Saves time when importing large product catalogs.
  • Compatible with multiple file formats and sources.
  • Ideal for advanced WooCommerce stores needing automation.

Cons

  • Requires the premium version for full functionality.
  • Can be slightly complex for beginners.

Frequently Asked Questions

Now, let’s look at some frequently asked questions about this topic.

Can I update product prices using code in WooCommerce?

Yes. WooCommerce provides hooks and functions like update_post_meta() and the WC_Product class, allowing you to update product prices programmatically using PHP.

Is it safe to update prices programmatically?

It is safe if done correctly. Always test your code on a staging site before applying it to your live store and keep backups of your database.

Can I bulk update prices using code or scripts?

Yes. You can loop through products using WC_Product_Query or get_posts() to apply bulk price updates based on your conditions.

Can I schedule automatic price changes?

Yes. You can use WordPress’ wp_schedule_event() function or plugins like WP Crontrol to schedule automated price updates.

Will programmatic price updates work for variable products?

Yes. You’ll need to loop through each variation and update its price individually using the appropriate variation IDs.

Are there plugins that can help with automatic price updates?

Yes. Plugins like Bulk Edit Products, Prices & Attributes or Advanced Bulk Edit allow price changes without custom coding.

How do I undo or roll back a programmatic price change?

If you have a backup of your database, you can restore it. Alternatively, create code logic to revert prices or use WooCommerce’s built-in product import/export tools.

Why are my programmatic updates not showing on the front end?

Clear all site caches, regenerate product lookup tables (WooCommerce → Status → Tools), and check that you updated both regular and sale prices correctly.

Conclusion

Learning how to update the product price programmatically in WooCommerce can give you a lot of flexibility. You can offer discounts to subscribed users, charge extra fees for customers who prefer faster delivery or additional packaging, and so on. And the best part is that you don’t need to install any plugins to do it.

In this guide, we’ve seen several examples of dynamically changing prices programmatically. However, that’s just the tip of the iceberg. WooCommerce offers endless possibilities, so we recommend experimenting with and customizing the scripts.

If you have any questions about the scripts, please let us know in the comments below. We’ll be happy to help.

Finally, if you want to improve your checkout process, check out our guide to optimizing the checkout.

12 comments

  • Por aqui DanielVT mi hermano, Excelente Pagina de Ayuda para los amantes de Wordpress. un Grato Saludo.

  • Hi
    I want only update subtoatl and price is defualt set like as you present in first screentshoot.
    For example $12 is product price and after update 12+15 = 27 is correct but in the cart ‘price’ column i want to show $12 and ‘subtota column $15.

  • Thank you so much for your hard work! Your site has helped me out a lot of times in difficult situations.
    Please tell me, is it possible to modify your code above so that the displayed price of the product changes when the quantity changes?
    In other words, so that a specific product with id 648 changes the displayed price if you increase its quantity?
    Roughly speaking:

    “`if ($product_id = 648 && $quantity >= 2)“` – the displayed regular price changes to another one. Not in the Cart! On the product page.
    I’ve already dug all over Google, but I haven’t found anything concrete 🙁
    Thank you in advance!

  • In the first example, the Ajax does not work, it does not update the price under the checkbox selection.

    • Hi Malwina.
      This script is not integrated with AJAX.
      You’ll need to adapt by yourself
      Cheers !

  • Hi,
    I wanted to ask, if i want to update product width.. can i use $cart_item_data[‘new_width’] ?
    And another question.. in some places i saw that they were using ‘new-price’, is it the same?
    Thank you 🙂

  • Hey,

    Love the write up, just one question. You changed the price when added to cart, I know there is a way to change the HTML of the price based on your calculation but I cant for the life remember. Any clues?

    Thanks

    • Hi Calum
      I’m glad you liked it!
      But It’s hard to help you without knowing exactly what you’re after.
      I think you could try running a new function when your recalculation hook is called. And insert html content using another hook.

  • Fantastic stuff thanks. One bug however, I have a product with many variations and different prices depending on the selected variation – this code basically gives the discount based on the lowest value variation.

    For example: Variation A costs $100, Variation B costs $200. When variation B is added to basket it changes the price to $80 instead of $160..

    Thanks.

    • Hi Nick, I’m happy you liked it !

      But these scripts will work only for simple products, you’ll need to customize the script in order to support variable products.
      Get the price of variation replacing this part:
      $product = wc_get_product( $product_id );
      $price = $product->get_price()

Leave your comment

Log into your account
Forgot your password?