Map custom User Fields

You can update User Fields that you have created on Discourse via SSO. This does not require a plugin. To do this, you need to know the name that Discourse uses in the database for the custom field. The easiest way I know of to do this is by going to your Admin / Customize / User Fields page and then loading the JSON version of the page. For example https://forum.example.com/admin/customize/user_fields.json

The JSON data of the page will look something like this:

{
user_fields: [
{
id: 12,
name: "News Letter",
description: "Send me a newsletter",
field_type: "confirm",
editable: false,
required: true,
show_on_profile: false,
show_on_user_card: false,
position: 3
},
{
id: 13,
name: "Company",
description: "Where do you work?",
field_type: "text",
editable: true,
required: false,
show_on_profile: true,
show_on_user_card: true,
position: 4
}
]
}

User custom fields are named user_field_<field_id>. This means that the name of the “News Letter” field from my JSON example is user_field_12, the name of the “Company” field is user_field_13. Use this information to update the SSO payload.

As an example, with the wpdc_sso_params filter that I mentioned in my previous post, the following code added to my theme’s functions.php file will set all users “Company” field to “acme” when they login via SSO. Replace my_namespace in the function name with a unique namespace for your site:

add_filter( 'wpdc_sso_params', 'my_namespace_set_discourse_custom_field', 10, 2 );
function my_namespace_set_discourse_custom_field( $sso_params, $user ) {
	$sso_params['custom.user_field_13'] = 'acme';

	return $sso_params;
}

To add fields that are based on WordPress user data from your site, use the function’s $user parameter to get details about your users.

3 Likes