如何在Woocommerce中以编程方式安排销售日期 [英] How to programmatically schedule sale dates in Woocommerce

查看:49
本文介绍了如何在Woocommerce中以编程方式安排销售日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试安排woo保存(发布)帖子时的woocommerce销售期.

Im trying to schedule the sale period in woocommerce when a post is saved (published).

我在下面尝试了两种方法,但是它们都不起作用.该代码在正确的时间被调用,只是不更新​​post meta.

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

}   

推荐答案

您可以使用以下方式之一:

You can use one of the following ways:

第一种方法-自WooCommerce 3以来:

1st Way - Since 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文件中.两种方法都可以.

Code goes in functions.php file of your active child theme (or active theme). Both ways work.

添加:

要使此情况仅当发布状态设置为发布" 时,您可以将以下内容添加到 IF 语句中现有条件:

To make that happen only when the post status is set on "publish", you can add the following to the IF statement existing conditions:

&& isset($_POST['post_status']) && $_POST['post_status'] === 'publish'

这篇关于如何在Woocommerce中以编程方式安排销售日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆