First, get_post_meta($order_id, '_payment_method', true )
or $order->get_payment_method()
完全相似 and 做同样的事.
不同之处在于第一个使用 Wordpress 函数来访问这些数据wp_postmeta
表,第二个是WC_Order
方法也将访问相同的数据wp_postmeta
table…
没有人比另一个人更好。
新的增强型重访代码(see 这个线程 https://stackoverflow.com/a/35689563/3730754用于解释).
实例 ID 是什么:
例如,如果运输方式费率 ID 为flat_rate:14
,实例 ID 为14
(唯一身份)
新版本代码:
add_action( 'woocommerce_payment_complete_order_status', 'auto_complete_paid_order_based_on_shipping_method', 10, 3 );
function auto_complete_paid_order_based_on_shipping_method( $status, $order_id, $order ) {
// HERE define the allowed shipping methods instance IDs
$allowed_shipping_methods_instance_ids = array( '14', '19' );
// Loop through order "shipping" items
foreach ( $order->get_shipping_methods() as $shipping_method ) {
if( in_array( $shipping_method->get_instance_id(), $allowed_shipping_methods_instance_ids ) ) {
return 'completed';
}
}
return $status;
}
代码位于活动子主题(或活动主题)的 function.php 文件中。经过测试并有效。
原答案:
下面的答案来自我前段时间做过的类似答案:
WooCommerce:自动完成付款订单 https://stackoverflow.com/questions/35686707/woocommerce-auto-complete-paid-orders-depending-on-payment-methods
add_action( 'woocommerce_thankyou', 'auto_complete_paid_order_based_on_shipping_method', 10, 1 );
function auto_complete_paid_order_based_on_shipping_method( $order_id ) {
if ( ! $order_id ) return;
// HERE define the allowed shipping methods IDs (can be names or slugs changing the code a bit)
$allowed_shipping_methods = array( 'flat_rate:14', 'flat_rate:19' );
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
// Get the shipping related data for this order:
$shipping_item = $order->get_items('shipping');
$item = reset($shipping_item);
$item_data = $item->get_data();
// Get the shipping method name, rate ID and type slug
$shipping_name = $item_data['name']; // Shipping method name
$method_rate_id = $item_data['method_id']; // Shipping method ID
$method_arr = explode( ':', $method_rate_id );
$method_type = $method_arr[0]; // Shipping method type slug
// No updated status for orders delivered with Bank wire, Cash on delivery and Cheque payment methods.
$avoided_statuses = array( 'bacs', 'cod', 'cheque');
if ( in_array( $order->get_payment_method(), $avoided_statuses ) ){
return;
}
// update status to "completed" for paid Orders and a defined shipping method ID
elseif ( in_array( $method_rate_id, $allowed_shipping_methods ) ){
$order->update_status( 'completed' );
}
}
代码位于活动子主题(或活动主题)的 function.php 文件中。
经过测试并有效。