不要使用init钩子,您应该尝试使用以下函数之一,它会自动完成处理订单总金额低于50美元强> (例如):
1) 使用woocommerce_order_status_processing action hook(最佳选择):
add_action( 'woocommerce_order_status_processing', 'auto_complete_processing_orders_based_on_total', 20, 4 );
function auto_complete_processing_orders_based_on_total( $order_id, $order ){
// HERE define the max total order amount
$max_total_limit = 50;
if ( $order->get_total() < $max_total_limit ) {
$order->update_status( 'completed' );
}
}
代码进入您的活动子主题(活动主题)的 function.php 文件中。经过测试并且可以工作。
2) 使用woocommerce_thankyou 动作挂钩(如果您的订单始终处于处理状态,这是一个不错的选择):
add_action( 'woocommerce_thankyou', 'thankyou_auto_complete_processing_orders_based_on_total', 90, 1 );
function thankyou_auto_complete_processing_orders_based_on_total( $order_id ){
if( ! $order = wc_get_order( $order_id ) ){
return;
}
// HERE define the max total order amount
$max_total_limit = 50;
if( $order->has_status('processing') && $order->get_total() < $max_total_limit ){
$order->update_status( 'completed' );
}
}
代码进入您的活动子主题(活动主题)的 function.php 文件中。经过测试并且可以工作。
3) 基于总量的批量更新处理订单(2种可能性):
A) 使用init hook (最好的方法):使用直接 SQL 查询的最轻量级和最有效的方式:
add_action( 'init', 'sql_auto_complete_processing_orders_based_on_total' );
function sql_auto_complete_processing_orders_based_on_total(){
// HERE define the max total order amount
$max_total_limit = 50;
global $wpdb;
// Very light bulk update direct SQL query
$orders_ids = $wpdb->query("
UPDATE {$wpdb->prefix}posts as a
JOIN {$wpdb->prefix}postmeta AS b ON a.ID = b.post_id
SET a.post_status = 'wc-completed'
WHERE a.post_status = 'wc-processing'
AND b.meta_key = '_order_total' AND b.meta_value < '$max_total_limit'
");
}
代码进入您的活动子主题(活动主题)的 function.php 文件中。经过测试并且可以工作。
B) 基于您的代码 使用 init 钩子 (非常重,但更兼容 woocommerce 中未来的数据库结构更改,如果发生的话天):
add_action( 'init', 'init_thankyou_auto_complete_processing_orders_based_on_total' );
function init_thankyou_auto_complete_processing_orders_based_on_total(){
// HERE define the max total order amount
$max_total_limit = 50;
// Get all processing orders
$orders = wc_get_orders( array( 'limit' => -1, 'status' => 'processing') );
if( sizeof($orders) > 0 ) {
// loop through processing orders
foreach( $orders as $order ) {
if( $order->get_total() < $max_total_limit ) {
$order->update_status( 'completed' );
}
}
}
}
代码进入您的活动子主题(活动主题)的 function.php 文件中。经过测试并且可以工作。
相关:WooCommerce: Auto complete paid Orders (depending on Payment methods)