I have some code in the functions.php
of a Wordpress / Woocommerce project, where I try to update a custom database table based on USER ID and ORDER ID:
global $wpdb;
$table = $table="wp_thegraffitiwall";
$user = get_current_user_id();
if($user == 0)
exit();
echo "Current User ID is ";
echo $user;
echo "Current Order ID is ";
$wpdb->update($table,$updateStuff,['userid'=>$user]);
// $wpdb->update($table,$updateStuff,['userid'=>$user] AND 'orderid'=>#orderid);
exit("Saved!");
As you can see I can retrieve the current USER ID and use it, but I am having trouble getting the current ORDER ID.
I have searched on Stackoverflow and tried things like:
$order->get_id();
But this does not work.
I want to assign the current ORDER ID to the $order_id and then use it in the update function further down which I have currently commented out.
The order ID only exist in Order received (thankyou) page and My Account > Order view pages in front end (for the current user). So your code is a bit incomplete as it should be in a hooked function, if used in function.php file of your theme.
Now you could try one of this hooked functions instead, where you will need to add the necessary code related to the $updateStuff
variable. Both functions will get triggered when order is created after checkout.
The first alternative (where you can use directly the $order_id
as it's an argument):
add_action( 'woocommerce_checkout_update_order_meta', 'custom_checkout_update_order', 25, 2 );
function custom_checkout_update_order( $order_id, $data ) {
global $wpdb;
// Get the user ID from the Order
$user_id = get_post_meta( $order_id, '_customer_user', true );
$updateStuff = 'something'; // <=== <=== <=== <=== HERE you add your code
$wpdb->update( 'wp_thegraffitiwall', $updateStuff, array('userid' => $userid) );
}
Code goes in function.php file of your active child theme (or active theme).
Or this one (where you can use directly the $order_id
as it's an argument):
add_action( 'woocommerce_thankyou', 'custom_thankyou_action', 20, 1 );
function custom_thankyou_action( $order_id ) {
if ( ! $order_id ) return; // Exit
global $wpdb;
// Get the user ID from the Order
$user_id = get_post_meta( $order_id, '_customer_user', true );
$updateStuff = 'something'; // <=== <=== <=== <=== HERE you add your code
$wpdb->update( 'wp_thegraffitiwall', $updateStuff, array('userid' => $userid) );
}
Code goes in function.php file of your active child theme (or active theme).