Im trying to schedule the sale period in woocommerce when a post is saved (published).
I have tried both methods below but neither of them are working. The code is being called at the right time, just not updating the post meta.
Neither methods are updating the sale schedule.
add_action('save_post_product', array($this, 'knpv_new_product_from_draft'), 10, 2);
add_action('edit_post_product', array($this, 'knpv_new_product_from_draft'), 10, 2);
public function knpv_new_product_from_draft($post_id, $post){
//Get todays date and the date 15 days from now
$datefrom = strtotime(date('Y-m-d'));
$dateto = strtotime(date('Y-m-d', strtotime('+15 days',$datefrom)));
//Method 1
$product = wc_get_product($post_id);
if( !empty(get_post_meta($post_id, '_sale_price', true)) ){
$product->set_date_on_sale_from( $datefrom );
$product->set_date_on_sale_to( $dateto );
}
$product->save();
//Method 2
$var = update_post_meta($post_id, '_sale_price_dates_from', $datefrom);
$var2 = update_post_meta($post_id, '_sale_price_dates_to', $dateto);
}
2
Answers
The reason this wasn't working was because the meta was being updated after the save_post action had finished. So I was updating the meta, then the empty values from the form were also updating them and clearing them.
So I did it like this.
You can use one of the following ways:
1st Way – Since WooCommerce 3:
2nd Way – the old way:
Code goes in functions.php file of your active child theme (or active theme). Both ways work.