Oluf Nielsen
Oluf Nielsen

Reputation: 779

Firing WordPress hook when user role is updated in code

I am trying to fire an event every time a users role has changed. So far I got this:

add_action( 'set_user_role', function( $user_id, $role, $old_roles )
  {
    error_log("usu fired2!");

    $user_info = get_userdata($user_id);
    $email = $user_info->user_email;

    error_log($email);
    error_log(print_r($old_roles, true));
    error_log($role);

    if ($role == "subscriber") {
      MC_user_tag_l2s($email, "klubmedlem", "active");
    } else {
      MC_user_tag_l2s($email, "klubmedlem", "inactive");
    }

  }, 10, 3 );

It works very well when I am updating the users role manually on the edit-profile page. However, it is not working when the users role is updated through code. I.e. when a user creates a subscription with WooCommerce subscriptions.

Any ideas as to which hook I should use instead?

Upvotes: 0

Views: 520

Answers (1)

Thomas LIBERATO
Thomas LIBERATO

Reputation: 333

It seems that you want to use the action woocommerce_subscriptions_updated_users_role

Description: When a subscription is activated, suspended, cancelled or expired, the user’s role will also be changed, which triggers the 'woocommerce_subscriptions_updated_users_role' hook.

Source: https://docs.woocommerce.com/document/subscriptions/develop/action-reference/

Upvotes: 1

Related Questions