What's the issue with my cURL request?

Unless I’m doing something wrong, the request to "/groups/${group_id}/members.json" is kind of unintuitive. It also doesn’t seem to be documented and can’t be viewed in the browser’s network tab when submitting the Discourse “Add User” form on a group’s page. Again, I could be doing something wrong.

In any case, the path for the request is /groups/${group_id}/members.json, with the group’s numerical ID substituted for group_id. The body of the request requires a group_id parameter, but that parameter needs to be set to the group’s name. So the args become something like this:

$group_id = 45;
$group_name = 'publishers';
$args     = array(
    'method' => 'DELETE', // or 'PUT'
	'body'   => array(
		// 'group_id'  => $group_name, edit: this param isn't needed, not sure what was going on when I was testing it.
		'usernames' => 'sally,Ben',
	)
);

// path:
/groups/${group_id}/members.json

If you have the WP Discourse plugin configured on your WordPress site, you can use its static discourse_request helper function to avoid having to use curl. Note that I linked to the static function that’s in the plugin-utilities file, but the namespace you need to use for external requests is from wp-discourse/lib/utilities.php at main · discourse/wp-discourse · GitHub.

use WPDiscourse\Utilities\Utilities as DiscourseUtilities;

function zalg_add_users_to_group() {
	$group_id = 45;
    $group_name = 'publishers';
    $method = 'PUT'; // 'PUT' to add users; 'DELETE' to remove users
	$args     = array(
		'method' => $method,
		'body'   => array(
			// 'group_id'  => $group_name, edit: this param isn't needed
			'usernames' => 'sally,Ben',
		)
	);
	$response = DiscourseUtilities::discourse_request( "/groups/${group_id}/members.json", $args );
    // return, log, or handle the response
}

If you are using WordPress as the SSO provider for Discourse, there’s a helper function that allows you to add one user to one or more groups:

function zalg_sso_add_users_to_group() {
    $user_id = 1; // the user's WordPress user ID
    $group_names = 'foo,bar,baz'; // one or more comma separated group names, with no spaces after commas!
    DiscourseUtilities::add_user_to_discourse_group($user_id, $group_names);
}

To add multiple users to a single group, you’d still need to use the discourse_request method that’s in the first code example.

3 Likes