在 WooCommerce 预订中使用什么钩子取消预订?

What hook to be used for cancelled booking in WooCommerce Bookings?

我正在尝试在取消预订后通过自定义插件向 SQL 查询 运行,更新自定义用户元数据。

这是我的代码:

function wporg_callback() {
    global $wpdb;

    $wpdb->query("UPDATE usermeta SET meta_value = 15 WHERE umeta_id = 131");
}

add_action('woocommerce_bookings_cancelled_booking', 'wporg_callback');

但是它不起作用。
查询有问题吗?是不是没有用到正确的动作?


编辑 - 我还尝试了以下但没有成功:

add_action('woocommerce_bookings_cancelled_booking', 'wporg_callback'); 
function wporg_callback( $booking_id ) { 
    // Add/Update custom user meta data 
    update_user_meta( 2, 'download_credits', 17 ); 
} 

更新:

要使用的正确挂钩是 woocommerce_booking_cancelled(复合挂钩),它允许您检索用户 ID 和 Add/update 自定义用户元数据,如下所示:

add_action('woocommerce_booking_cancelled', 'booking_cancelled_transition_to_callback', 10, 2 );
function booking_cancelled_transition_to_callback( $booking_id, $booking ) {
    // Get the user ID from the Booking ID
    $user_id = get_post_field ('post_author', $booking_id);
    
    $download_credits = get_post_meta( $booking_id, '_booking_cost', true );
    
    // Add/Update custom user meta data
    update_user_meta( $user_id, 'download_credits', $download_credits );
}

代码进入您的活动子主题(或主题)的 functions.php 文件。已测试并有效。


如何获取预订数据 (来自订单中显示的预订ID):

  • 转到 wp_postmeta table 下的数据库,从 post_id(即预订 ID)中获取所需的 meta_key

  • get_post_meta() WordPress 函数中使用 元键 ,例如:

     $meta_value = get_post_meta($booking_id, 'the_meta_key', true); 
    

Notes:

  • An SQL query is not needed to add/update custom user meta data, as you can use instead the dedicated Wordpress function update_user_meta().

  • I couldn't make it work using woocommerce_bookings_cancelled_booking hook.


WooCommerce Bookings action and filters hooks developer documentation