I am making a function which needs to be called after an order is completed within WooCommerce. For this I’m using the *’woocommerce_order_status_completed’* hook.
I want to check if the order has a product belonging to a specific product category.
If this is the case, the user will be added to a group within WordPress. To handle the group logic, I’m making use of another plugin’s API. This method needs the *group_id* and the *user_id*.
The only thing I’m missing is getting the *user_id*.
How can I get the user (in detail: the id), from my WooCommerce Order?
code:
function isa_set_isa_member_group_after_order_completed($order_id) {
$order = new WC_Order( $order_id );
$items = $order->get_items();
foreach($items as $item) {
$product = $order->get_product_from_item($item);
$has_membership_product = has_term('Lidmaatschap','product_cat',$product->post);
if($has_membership_product) {
break;
}
}
$group = Groups_Group::read_by_name('ISA Leden');
if(!group) {
return; // TODO: Add error message + email?
}
$user_id = 0 // TODO: Get user id from order.
$user_group = array(
"user_id" => $user_id,
"group_id" => $group->group_id
);
$result = Groups_User_Group::create($user_group);
if(!result) {
return; // TODO: Add error message + email?
}
}
Technical details:
WordPress version: 3.8
WooCommerce version: 2.1
From the
__get()
method in theWC_Order
class you can see that theuser_id
property is taken from/stored as_customer_user
post meta for the order in question.So in your code you can grab the user id like so:
I presume you’re not going to allow guest checkout, but you might want some kind of fallback in case there isn’t a user id.
Update for WooCommerce 3.0
Disregard all of the above. As pointed out in the comments there are direct methods for getting this information. In fact, almost all “magic methods” have been removed and directly accessing object properties will throw PHP warnings.