How to update woocommerce price programmatically using crud method?

To update the price of a WooCommerce product programmatically using the CRUD (Create, Read, Update, Delete) method, you can use the WooCommerce Product CRUD classes. Here’s a step-by-step guide on how to do it:

  1. Get the Product Instance: Before you can update the price, you need to get an instance of the product you want to update. You can do this using the wc_get_product() function and passing the product ID as an argument.
  2. Update the Price: Once you have the product instance, you can use the set_regular_price() and set_sale_price() methods to update the regular and sale prices, respectively.
  3. Save the Product: After updating the price, you need to save the product to store the changes in the database. You can do this using the save() method.

Here’s a code example:

// Get the product instance
$product = wc_get_product( $product_id );

// Check if product exists
if( $product ) {
    // Set the regular price
    $product->set_regular_price( '100' );  // Set the regular price to 100

    // Set the sale price (optional)
    $product->set_sale_price( '80' );  // Set the sale price to 80

    // Save the product with the updated price
    $product->save();
}

Replace $product_id with the ID of the product you want to update. Adjust the values ‘100’ and ’80’ to the desired regular and sale prices, respectively.

Note: Always make sure to backup your website and database before making any programmatic changes. This ensures that you can revert back to a previous state in case something goes wrong.

Similar Posts