为了账号安全,请及时绑定邮箱和手机立即绑定

如何以编程方式在 Woocommerce 中安排销售日期

如何以编程方式在 Woocommerce 中安排销售日期

PHP
慕田峪4524236 2023-04-21 15:13:34
我试图在保存(发布)帖子时安排 woocommerce 中的销售期。我已经尝试了下面的两种方法,但它们都不起作用。代码在正确的时间被调用,只是不更新帖子元。这两种方法都没有更新销售时间表。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 回答

?
侃侃无极

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'


查看完整回答
反对 回复 2023-04-21
?
慕虎7371278

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'));


  }


查看完整回答
反对 回复 2023-04-21
  • 2 回答
  • 0 关注
  • 76 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信