2 回答

TA貢獻2051條經驗 獲得超10個贊
您可以使用以下方法之一:
第一種方式- 自 WooCommerce 3 以來:
add_action( 'woocommerce_admin_process_product_object', array($this, 'save_wc_product_meta_data') );
public function save_wc_product_meta_data($product) {
if( isset( $_POST['_sale_price'] ) && $_POST['_sale_price'] >= 0 ){
$product->set_date_on_sale_from( strtotime(date('Y-m-d')));
$product->set_date_on_sale_to( strtotime( date('Y-m-d', strtotime('+15 days'))));
}
}
第二種方式- 舊方式:
add_action( 'woocommerce_process_product_meta', array($this, 'save_wc_product_meta_data') );
public function save_wc_product_meta_data($product_id) {
if( get_post_meta($product_id, '_sale_price', true) >= 0 ){
update_post_meta($product_id, '_sale_price_dates_from', strtotime(date('Y-m-d')));
update_post_meta($product_id, '_sale_price_dates_to', strtotime( date('Y-m-d', strtotime('+15 days'))));
}
}
代碼進入您的活動子主題(或活動主題)的 functions.php 文件。兩種方式都有效。
添加:
要僅在發布狀態設置為 "publish" 時發生這種情況,您可以將以下內容添加到IF語句現有條件中:
&& isset($_POST['post_status']) && $_POST['post_status'] === 'publish'

TA貢獻1802條經驗 獲得超4個贊
這不起作用的原因是元數據在 save_post 操作完成后正在更新。所以我正在更新元數據,然后表單中的空值也在更新并清除它們。
所以我這樣做了。
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){
//If the post is being published.
if (get_post_status($post_id) == 'publish') {
//Set the values from the posted form data.
$_POST['_sale_price_dates_from'] = date('Y-m-d');
$_POST['_sale_price_dates_to'] = date('Y-m-d', strtotime($datefrom.' +15 days'));
}
}
- 2 回答
- 0 關注
- 126 瀏覽
添加回答
舉報