I'm working on WooCommerce with two product types. I need some of them ($products_to_check) to create an specific role account (subscriber) and the rest of them another one (customer, which is the default one for WooCommerce).
The thing is, if I have an user who's already a costumer, I don't want him to change its role to subscriber (so I check if he's logged in, which mean he's not a new costumer and have a previous defined role). On the other hand, if a subscriber purchase one of the products not included in $products_to_check, he should get a role upgrade (from subscriber to costumer).
This is my function, which is not working but I don't really know why.
add_action( 'woocommerce_order_status_completed', 'change_role_on_purchase' );
function change_role_on_purchase( $order_id ) {
$order = wc_get_order( $order_id );
$items = $order->get_items();
$products_to_check = array( ... );
$user = new WP_User( $order->user_id );
$user_meta = get_userdata( $order->user_id );
$user_roles = $user_meta->roles;
foreach ( $items as $item ) {
if ( $order->user_id > 0 && in_array( $item['product_id'], $products_to_check ) ) {
if (!is_user_logged_in()){
$user->set_role( 'subscriber' );
}
}
elseif ( $order->user_id > 0 && !(in_array( $item['product_id'], $products_to_check)) ) {
if (is_user_logged_in() && in_array('subscriber', $user_roles)){
$user->set_role( 'customer' );
}
}
}
}
I'd really appreciate any help on this issue. What am I doing wrong?
There are several things you need to take note here.
user_register
is the hook to use for newly registered users. So first make sure your hook triggers after or overrides the WooCommerce user role hooks. And I think you can do away completely with the new or old user logic, as the only important thing is whether they purchased a product that's going to upgrade them; if not, they should have the default role.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.