PHP从今天开始计算过去的日期

时间:2020-02-01 10:20:36

标签: php wordpress date woocommerce

我创建了一个PHP函数,该函数计算WordPress / WooCommerce订单的年龄。如果订单早于90天,则应取消订单。该功能曾经完美运行。但是,自从新的2020年以来,它已经停止工作。我认为这是因为该函数对从今天开始的-90天是2019年感到困惑,所以我如何才能使用过去的几年/ 2019年进行计算?

我尝试使用WordPress Codex而不是mdy使用不同的日期格式。但是,这似乎没有什么区别。

function expire_after_x_days(){
    global $wpdb;
    // Get current time
    $today = date("m/d/y");

    // set time to expire
    $time_to_expire = "-90 days";
    $expiration_date = date("m/d/y", strtotime( $today . $time_to_expire));

    // Get orders with processing status
    $result = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_type = 'shop_order' AND post_status = 'wc-processing'");

    if( !empty($result)) foreach ($result as $order){
        // Get order's time
        $order_time = get_the_time('m/d/y', $order->ID );

        // Compare order's time with current time
        if ( $order_time < $expiration_date ){

            // Update order status    
            $orders = array();
            $orders['ID'] = $order->ID;
            $orders['post_status'] = 'wc-cancelled';
            wp_update_post( $orders );
        }
    }
} 

add_action( 'admin_footer', 'expire_after_x_days' );

3 个答案:

答案 0 :(得分:2)

您将这些变量视为DateTime实例,但它们是字符串。 ffmpeg() .input("/home/yom/test/Kent_4K_Landscape.mp4") .inputOption([ "-vsync 0", "-hwaccel cuvid", "-hwaccel_device 0", "-c:v h264_cuvid" ]) .videoCodec("h264_nvenc") .videoFilter("scale_npp=-1:720") .native() .audioCodec('aac') .audioBitrate(128) .audioChannels(2) .videoBitrate(5000) .save("/home/yom/test/out.mp4") .on('error', (err) => { console.log(err) }) .on('end', () => { console.log("done") }); 会按字母顺序比较字符串,而不是按日期含义进行比较。改用DateTime类(https://www.php.net/manual/en/class.datetime.php)。

答案 1 :(得分:2)

您可以通过运行带有UPDATE子句的WHERE查询来简化很多操作,只提取90天以上的订单。无需全部获取它们并遍历结果。

您需要将post_created设置为列的实际名称。

function expire_after_x_days() {
    global $wpdb;

    $result = $wpdb->query("UPDATE $wpdb->posts 
                            SET post_status = 'wc-cancelled'
                            WHERE post_type = 'shop_order' 
                              AND post_status = 'wc-processing'
                              AND post_created < DATE_SUB(NOW(), INTERVAL 90 DAY)");
} 

答案 2 :(得分:1)

请将日期格式从 m / d / y 更改为 Y-m-d 。请参见下面的代码。

您还可以通过修改$ order_time = '12 / 11/18'来手动检查;

public function p($param = "none") {
    echo $param;
}