Search code examples
phpwordpresswoocommerceproduct

How to set product's sale & regular price programmatically in WooCommerce


I need to change the product's regular and sale price in WooCommerce.

I can update the regular price using:

update_post_meta( $product_id, '_price', 500 );

But I want to change sale price also. Some products don't have a _sale meta key, so I can't do the same thing I did to regular price.


Solution

  • You are actually using the old way to set product prices… There are 2 ways:

    A) Using this old way,
    1. to set the regular price only, you should use:

      update_post_meta( $product_id, '_regular_price', 500 );
      update_post_meta( $product_id, '_price', 500 );
      
    2. to set the sale price and the regular price, you should use:

      update_post_meta( $product_id, '_sale_price', 450 );
      update_post_meta( $product_id, '_price', 450 );
      update_post_meta( $product_id, '_regular_price', 500 );
      
    B) The new way (Since WooCommerce 3):

    As WooCommerce is migrating to custom tables, and for other reasons, it's better to use all available WC_Product setter methods

    For product prices, you will use the following:

    // Get an instance of the WC_Product object
    $product = wc_get_product( $product_id );
    
    $regular_price = 500; // Define the regular price
    $sale_price    = 465; // Define the sale price (optional)
    
    // Set product sale price
    if ( isset($sale_price) && ! empty($sale_price) ) {
        $product->set_sale_price($sale_price);
    
        $product->set_price($sale_price); // Set active price with sale price
    } else {
        $product->set_price($regular_price); // Set active price with regular price
    }
    // Set product regular price
    $product->set_regular_price($regular_price);
    
    // Sync data, refresh caches and saved data to the database
    $product->save();