Skip to:
Content
Pages
Categories
Search
Top
Bottom

Auto join group based on role


  • dcsenterprise
    Participant

    @dcsenterprise

    Hello,
    I have users with the role of Vendor, based on WCVendors and WooCommerce.
    Once the person submits application to be a Vendor and it is accepted, the role of Vendor is added to them.

    I have a Group for Vendors. I need a way for them to be added to the Vendors Group once the role is added.

    This code to auto add new members to a group seems the likely place to start but I don’t know how to do it. Would someone PLEASE help me with this?

    //Automatically add new users to a group
    function automatic_group_membership( $user_id ) {
    if( !$user_id )
    return false;
    
    groups_accept_invite( $user_id, 2 );
    }
    add_action( 'user_register', 'automatic_group_membership' ); 

    To a newbie like me seems like this can be altered to $role , correct?

Viewing 3 replies - 1 through 3 (of 3 total)

  • danbp
    Participant

    @danbp

    Hi @dcsenterprise,

    in brief, the snippet tells 'user_register to add a new user automatically to a group after the register process.

    If this is the scenario you want to use, you have to ensure that the Vendor role is in a xprofile field or at least, that this role is somewhere on the user profile, added by the WC plugin.

    Assuming that it’s the case, you can use this:

    function automatic_group_membership( $user_id ) {
    
    if( !$user_id ) return false;
    
       $join_group = xprofile_get_field_data('WCRole', $user_id); // field name (case sensitive) containing the role
       // conditionnal
       if ($join_group == 'vendor') // role name
          $group_id = '8'; // the id of the Vendor group to auto-join
    
    // action
    groups_accept_invite( $user_id, $group_id );
    
    }
    add_action( 'bp_core_activated_user', 'automatic_group_membership' );

    How it works ?

    – a field or select field on register page, with evtl. options
    field name = WCRole
    option0 = vendor
    option1 = manager
    option3 = director
    etc…

    If several options for different groups, you simply add it as conditionnal to the function:

     if...
     $group_id =

    Hope to be clear !


    shanebp
    Moderator

    @shanebp

    If the role is set to vendor and xprofile fields are not involved, then there is a WP hook for that.

    Assuming the group_id is 8, try:

    function jeffery_join_vendor_group( $user_id, $role, $old_roles ) {
    	if( $role == 'vendor' ) {
    		groups_accept_invite( $user_id, 8 );
    	}
    }
    add_action( 'set_user_role', 'jeffery_join_vendor_group', 11, 3 );

    dcsenterprise
    Participant

    @dcsenterprise

    It’s been a while since I’ve been back here, but a belated THANK YOU to @shanebp and @danbp

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.
Skip to toolbar