我正在尝试创建一个应该检查向WooCommerce商店的订单的函数。如果订单的状态尚未从处理中从处理中更改为10天内完成,则功能应取消订单。
我找到了WPDB,我认为我已经设法进行了查找以找到超过10天的订单。有人可以将我指向如何从这里前进的正确方向吗?我假设我必须创建一个包含WC_ORDER :: UPDATE_STATUS((的函数,以更新订单状态。我只是不知道如何将所有这些联系在一起。
我一直在查看WordPress codex并找到了WPDB,其中包含一组用于与数据库交互的功能。我假设我必须在功能中使用wpdb,但是dunno如何从这里进行。
我也一直在考虑用真正的cron替换本机WordPress Cron,该Cron检查日期并更新订单状态。但是,经过一些研究,我认为这是解决我的问题的一种太复杂的方法。
function get_processing_expiry() {
global $wpdb;
$processing_expiry = $wpdb->get_col( $wpdb->prepare( "
SELECT posts.ID
FROM {$wpdb->posts} AS posts
WHERE posts.post_status = 'wc-processing'
AND posts.post_date < %s
", date( 'Y-m-d H:i:s', strtotime('-10 days') ) ) );
return $processing_expiry;
}
我期望订单状态从处理转换为取消订单已有十天以上的时间。
此功能将处理它:
function expire_after_x_days(){
global $wpdb;
// Get current time
$today = date("mdy");
// set time to expire
$time_to_expire = "-10 days";
$expiration_date = date("mdy", 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('mdy', $order->ID );
// Compare order's time with current time -10 days
if ( $order_time < $expiration_date ){
// Update order status
$orders = array();
$orders['ID'] = $order->ID;
$orders['post_status'] = 'wc-cancelled';
wp_update_post( $orders );
}
}
}
// Use the best HOOK for your case
add_action( 'admin_footer', 'expire_after_x_days' );
// OR simply call the function if you are pasting this in your functions.php
在mySQL中,您有很多日期和时间功能可以检查记录是否大于10天。为此,您可以使用INTERVAL
类似的东西:
SELECT posts.ID
FROM {$wpdb->posts} AS posts
WHERE posts.post_status = 'wc-processing'
AND posts.post_date < NOW() - INTERVAL 10 DAY
然后,您只能使用SQL来解决它。
https://dev.mysql.com/doc/refman/5.5/en/date-and-pime-functions.html
您也可以无需WP即使使用MySQL计划的事件也可以实现这一目标每天安排活动或某个间隔。
CREATE EVENT Cencel_Orders_Event
ON SCHEDULE EVERY 5 SECOND
DO
CALL Cancel_Orders();
请参阅http://www.mysqltutorial.org/mysql-triggers/working-mysql-scheduled-event/