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

Let’s say you want to add link on user field that contains Twitter username, clicking on username should take user to Twitter profile. Let’s do it!

Create a custom user field

Create a new user field with name Twitter that will store user’s Twitter username.

Make sure “Show on public profile?” option is enabled.

Add custom CSS

Paste this CSS code in Admin > Customize > CSS/HTML > CSS section:

.public-user-field.twitter {
  display: none;
}

#user-card .metadata h3 {
  float: left;
}

h3.user-card-public-field {
 clear: both;   
}

Add custom JS:

Paste this JS code in Admin > Customize > CSS/HTML > </head> section:

<script type="text/discourse-plugin" version="0.8.7">
    api.registerConnectorClass('user-profile-primary', 'twitter-link', {
      setupComponent(args, component) {
        component.set('twitterLink', args.model.get('twitterLink'));
      }
    });

    api.registerConnectorClass('user-card-metadata', 'twitter-link', {
      setupComponent(args, component) {
        component.set('twitterLink', args.user.get('twitterLink'));
      }
    });

    api.modifyClass('model:user', {
      twitterLink: function() {
          const siteUserFields = Discourse.Site.currentProp('user_fields');
          if (!Ember.isEmpty(siteUserFields)) {
            const twitterUsernameField = siteUserFields.filterBy('name', 'Twitter')[0]
            if (!twitterUsernameField) {
              return null;
            }
            const userFieldId = twitterUsernameField.get('id');
            const userFields = this.get('user_fields');
            if (userFields && userFields[userFieldId]) {
              const url = "https://twitter.com/" + userFields[userFieldId];
              const link = "<a href='"+url+"' target='_blank'>@"+userFields[userFieldId]+"</a>";
              return Ember.Object.create({ link, name: twitterUsernameField.get('name') });
            } else {
              return null;
            }
          }
      }.property('user_fields.@each.value')
    });
</script>

<script type='text/x-handlebars' data-template-name='/connectors/user-profile-primary/twitter-link'>
  {{#if twitterLink}}
    <div class="public-user-fields">
      <div class="public-user-field">
        <span class="user-field-name">{{twitterLink.name}}</span>:
        <span class="user-field-value">{{{twitterLink.link}}}</span>
      </div>
    </div>
  {{/if}}
</script>

<script type='text/x-handlebars' data-template-name='/connectors/user-card-metadata/twitter-link'>
  {{#if twitterLink}}
    <h3 class="user-card-public-field">
      <span class="user-field-name">{{twitterLink.name}}</span>:
      <span class="user-field-value">{{{twitterLink.link}}}</span>
    </h3>
  {{/if}}
</script>

Voilà :tada:

That’s it, you will now see Twitter link on user profile page:

and user card:

17 Likes