I have this function which get fire when a page loads. It checks that the post type is ‘product’ and this case I need to change the product price and save the page.
I works fine, but I need to know how to set the new product price.
function changeAndSave( $array ) {
$post_type = get_post_type();
if ($post_type == "product"){
/*GET THE PRODUCT*/
global $product;
$product_id=$product->id;
/*GET CURRENT PRICE*/
$currentPrice=$product->get_price_html();
/*SET NEW PRICE*/
/* HERE.... ¿¿ how do I set my new price */
$newPrice = 100€;
/*SAVE THE PRODUCT*/
$product = wc_get_product($product_id);
$product->save();
}
};
// add the action
add_action( 'loop_start', 'changeAndSave', 10, 1 );
UPDATE: I tried this, but not working:
function changeAndSave( $array ) {
$post_type = get_post_type();
if ($post_type == "product"){
/*GET THE PRODUCT*/
global $product;
$product_id=$product->id;
$product = wc_get_product($product_id);
/*GET CURRENT PRICE*/
$currentPrice=$product->get_price_html();
/*SET NEW PRICE*/
$newRegularPrice = 81;
$product->set_regular_price($newRegularPrice);
/*SAVE THE PRODUCT*/
$product->save();
}
};
// add the action
add_action( 'loop_start', 'changeAndSave', 10, 1 );
2
Answers
You may try this code blocks with given product IDs inside your code.
To update regular prices:
To update sale prices:
Update – depending on your comment:
If it is a simple product:
If it is a variation product, use “update_post_meta” function.
Also you may check:
1 – Woo-commerce 3.0 single product price is not changing properly
2 – Update all variations prices of a variable product in Woocommerce
Updated
First, you are not using the right hook for that as it requires to be trigger before the page load.
Try the following (for simple products):
Code goes in functions.php file of your active child theme (or active theme). Tested and works.