我正在使用 WooCommerce 和 WooCommerce Bookings 插件。
当所有使用“货到付款”付款方式的预订处于“未付款”或“待处理”状态时,我想将其状态更新为“已确认”。目前,它们被设置为“无偿”。
这是我的代码尝试:
add_action('woocommerce_thankyou', 'set_cod_booking_status_to_confirmed', 10, 1);
function set_cod_booking_status_to_confirmed($order_id) {
$order = wc_get_order($order_id);
// Check if the payment method is Cash on Delivery
if ( $order->get_payment_method() === 'cod' ) {
// Get all bookings associated with this order
$bookings = WC_Bookings_Controller::get_bookings_for_order($order_id);
// Check if there are bookings
if (!empty($bookings)) {
// Get the first booking (if you want to confirm only the first one)
$booking = reset($bookings);
// Update the status to confirmed if it's unpaid or pending
if ($booking->get_status() === 'unpaid' || $booking->get_status() ===
'pending') {
$booking->update_status('confirmed');
}
}
}
}
不幸的是,它没有按预期工作。当我创建新的预订订单时,在预订页面上会抛出一条错误,提示“创建您的预订时遇到错误”。然而,预订仍然成功创建,状态为“未付款”。
如何将 WooCommerce 中的货到付款订单的预订状态更新为确认?
请注意,WooCommerce Bookings 中不存在
get_bookings_for_order()
方法。这就是引发错误的问题。
现在,由于使用货到付款 (cod) 付款方式支付的订单始终处于处理状态,因此最好使用
woocommerce_order_status_processing
挂钩,例如:
add_action('woocommerce_order_status_processing', 'set_booking_status_confirmed_for_cod_payment', 10, 2);
function set_booking_status_confirmed_for_cod_payment( $order_id, $order ) {
// Check if the payment method is Cash on Delivery
if ( $order->get_payment_method() === 'cod' ) {
// Get all booking Ids from the order ID
$booking_ids = (array) WC_Booking_Data_Store::get_booking_ids_from_order_id( $order_id );
if ( $booking_ids ) {
// Loop through bookings
foreach ( $booking_ids as $booking_id ) {
// Get an instance of the WC_Booking Object
$booking = new WC_Booking( $booking_id );
// Update booking status to confirmed if it's unpaid or pending
if ( in_array( $booking->get_status(), ['unpaid', 'pending'], true ) ) {
$booking->update_status('confirmed');
}
}
}
}
}
应该可以。