solo22x
solo22x

Reputation: 23

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

I'm trying to make an SQL query to run upon cancellation of a booking, via a custom plugin, updating custom user meta data.

Here's my code:

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');

But It's not working.
Is there something wrong with the query? Is the right action not being used?


Edit - I Also tried the following without success:

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 ); 
} 

Upvotes: 2

Views: 652

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254363

Updated:

The correct hook to be used is woocommerce_booking_cancelled (a composite hook) that will allow you to retrieve the user ID and to Add/update custom user meta data like below:

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 );
}

Code goes in functions.php file of your active child theme (or theme). Tested and works.


How to get the booking data (from the booking ID displayed in the order):

  • Go to your database under wp_postmeta table to get the desired meta_key from the post_id (that is the booking ID)

  • Use that meta key in get_post_meta() WordPress function like:

     $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

Upvotes: 1

Related Questions