I cannot add user to the discouse forum from a wordpress website when user added in a membership

To add to what @Firepup650 wrote, when your code calls

DiscourseUtilities::add_user_to_discourse_group($user_id, $s2member_level_2_groups);

it is calling a helper function that makes a request to the Discourse sync_sso route: Sync DiscourseConnect user data with the sync_sso route. That request is used to either update an existing user, or to create a new users. If the user with $user_id has never logged into your Discourse site, a new user will be created. They should still be added to the groups without any problem, but it will generate a notification for moderators because your site has enabled the must approve users site setting:

1 Like