Website Building » WooCommerce » How Do I Change Product Pricing Programmatically in WooCommerce?

How Do I Change Product Pricing Programmatically in WooCommerce?

Last updated on January 19, 2023 @ 4:02 pm

It is no secret that WooCommerce is one of the most popular eCommerce platforms on the market. Due to its popularity, there are a number of different ways that you can change product pricing programmatically in WooCommerce. In this article, we will discuss some of the most popular methods.

    1. Use the wc_get_product Function

    One way to programmatically change product pricing in WooCommerce is by using the wc_get_product function. This function allows you to get a product object by its ID. Once you have the product object, you can easily change its price using the set_price method.

    PRO TIP: If you are changing product prices programmatically in WooCommerce, be aware that this may have unintended consequences if not done correctly. For example, if you change a product’s price and then save the changes, any active price filters will no longer work correctly. In addition, any coupons or discounts that are based on the product’s original price will also be affected.
    $product = wc_get_product( $product_id );
    $product->set_price( 10 );
    $product->save();

    2. Use the update_post_meta Function

    Another way to programmatically change product pricing in WooCommerce is by using the update_post_meta function. This function allows you to update the price meta field for a given product. Once you have updated the price meta field, you can then save the product using the wp_update_post function.

    update_post_meta( $product_id, '_price', 10 );
    wp_update_post( array( 'ID' => $product_id ) );

Drew Clemente

Drew Clemente

Devops & Sysadmin engineer. I basically build infrastructure online.