Change author url in WP to Discourse profile

(David Kingham) #1

I would like to change the author link in wordpress posts:

To link to the authors profile in Discourse. I found this snippet which is similar to what I want to achieve, I modified it slightly.

  add_filter( 'author_link', 'change_author_link', 10, 1  );

  function change_author_link($link) {
   $username=get_the_author_meta('user_nicename');


  $link = 'https://community.naturephotographers.network/u/' . $username;
   return $link;
 }

But I don’t know how to retrieve the discourse username from wordpress, the get_the_author_meta('user_nicename'); is what’s tripping me up. Thanks!

3 Likes
(Simon Cossar) #2

For users who have set their Discourse username on WordPress, you can get the username with:

get_user_meta( $user_id, 'discourse_username', true );

$user_id needs to be set to the user’s WordPress user ID. Since it’s possible that not all authors will have set their Discourse username, you should probably check that the value returned isn’t empty before creating the link.

2 Likes
(David Kingham) #3

Thanks Simon, any idea why this would not be working?

add_filter( 'author_link', 'change_author_link', 10, 1  );

$user_id=the_author_meta('ID');

function change_author_link($link) {
   $username = get_user_meta( $user_id, 'discourse_username', true );
   $link = 'https://community.naturephotographers.network/u/' .$username;
   return $link;
 }
(Simon Cossar) #4

Yes, $user_id isn’t available inside of your function. You need to pass the author’s id to the function as a parameter. Try this code. It also checks if the Discourse username has been set. If it’s not set, the default author link will be returned.

add_filter( 'author_link', 'wpdc_modify_author_link', 10, 2 );
function wpdc_modify_author_link( $link, $author_id ) {
    $discourse_username = get_user_meta( $author_id, 'discourse_username', true );
    if ( ! empty( $discourse_username ) ) {
        return "https://community.naturephotographers.network/u/$discourse_username";
    }

	return $link;
}
2 Likes
(David Kingham) #5

Brilliant, thank you Simon!

(system) closed #6

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.