(Retired) Use an ID in a custom user field to link to a user's external profile

My solution seems wrong. I’ll look at this some more when I get a chance.

Edit:
I was having some trouble understanding why this works, but after looking through the code a bit more this seems to make sense as a way of setting custom fields through SSO.

Create a user field on Discourse in the way outlined in the OP and then go to your profile as an admin and add a value (any value) to it. You can then go to the Discourse rails console and enter:

UserCustomField.all

A list of all the user_custom_fields on your site will be returned. It will be made up of one or more entries that look something like this:

#<UserCustomField:0x007fa02bb39d18 id: 18, user_id: 1, name: "user_field_8", value: "test value", created_at: Wed, 07 Jun 2017 01:48:10 UTC +00:00, updated_at: Wed, 07 Jun 2017 01:48:10 UTC +00:00>]
Look for the entry that has a value attribute that matches the value you just saved in your custom field. Copy the name of that field into a function on your WordPress site that is something like this:

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_7'] = $user->ID;

    return $sso_params;
}

To use the code in the OP, replace the name value (‘User Profile’) in this line:
const externalUserIdField = siteUserFields.filterBy('name', 'User Profile')[0]
with whatever you have called the field you added on Discourse. This is the part of the code that I wasn’t understanding, but it makes more sense after looking at this: https://github.com/discourse/discourse/blob/master/app/controllers/users_controller.rb#L99

Unless there is a better way to do this, I’ll add it to the WP Discourse Plugin Tips and Tricks topic.

1 Like