Automatically Adding New Users (from WP integration) To A Group

Yes, that’s the example that is missing from the topic I linked to. You can add users to a group as a part of the SSO login process by using the add_groups SSO parameter. By default, the WP DIscourse plugin doesn’t send this parameter with the SSO payload, but the plugin has a filter that can be used to add this parameter to the SSO payload.

The following code, added to your theme’s functions.php file, or to a plugin, should work for you. You can add users to multiple groups in this way. The add_groups parameter accepts a comma separate list of group names (with no spaces before or after the commas.):

add_filter( 'wpdc_sso_params', 'wpdc_custom_sso_params' );
function wpdc_custom_sso_params( $params ) {
    $params['add_groups'] = 'your_group_name'; 

    return $params;
}

If you only wanted to add specific users to the group, you could call the function like this:

add_filter( 'wpdc_sso_params', 'wpdc_custom_sso_params', 10, 2 );
function wpdc_custom_sso_params( $params, $user ) {
    if (/*add a condition here to check if the user should be added to the group */) {        
        $params['add_groups'] = 'your_group_name'; 
    }

    return $params;
}

You can also remove users from groups with the remove_groups SSO parameter.

add_filter( 'wpdc_sso_params', 'wpdc_custom_sso_params' );
function wpdc_custom_sso_params( $params ) {
    $params['remove_groups'] = 'your_group_name'; 

    return $params;
}

or

add_filter( 'wpdc_sso_params', 'wpdc_custom_sso_params', 10, 2 );
function wpdc_custom_sso_params( $params, $user ) {
    if (/*add a condition here to check if the user should be removed from the group */) {        
        $params['remove_groups'] = 'your_group_name'; 
    }

    return $params;
}

The main downside to this approach compared to using the add_user_to_discourse_group function that I linked to is that it requires existing users to log out and then log back into Discourse before their group memberships will be updated.

5 Likes