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



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

我尝试使用WordPress编解码器而不是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' );

您可以通过运行带有WHERE子句的UPDATE查询来简化此操作,以仅获取超过 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)");
} 

您将这些变量视为 DateTime 实例,但它们是字符串。此$order_time < $expiration_date按字母顺序比较字符串,而不是按日期含义进行比较。请改用日期时间类 (https://www.php.net/manual/en/class.datetime.php(。

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

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

function expire_after_x_days(){
global $wpdb;
// Get current time
$today = date("Y-m-d");
// set time to expire
$time_to_expire = "-90 days";
$expiration_date = date("Y-m-d", 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('Y-m-d', $order->ID );
// Compare order's time with current time
//$order_time = '12/11/18';
if ( $order_time < $expiration_date ){
//die("olde");
// Update order status    
$orders = array();
$orders['ID'] = $order->ID;
$orders['post_status'] = 'wc-cancelled';
wp_update_post( $orders );
}else{
//echo 'not old date';die;
}
}
}
} 
add_action( 'admin_footer', 'expire_after_x_days' );

相关内容

最新更新