0

I have created a website whereby users register and create their own templated profile pages. The profile pages are automatically created as Custom Posts upon registration, with the user being set as the Author of their specific post (profile).

(Users can only ever have one Custom Post)

I want to redirect a "dumb" URL like www.website.com/my-profile to a user's custom post when they are logged in.

For example, when John Smith visits www.website.com/my-profile he is directed to his profile page: www.website.com/users/john.smith

I have found many PHP solutions going the other way, but I can't seem to find a solution that does what I need. Any help would be greatly appreciated. Thanks!

Andrew
  • 65
  • 5
  • Have you tried using https://developer.wordpress.org/reference/functions/wp_safe_redirect/ – Leland Oct 12 '21 at 07:14
  • Hi Leland. Thanks so much for the response! I have had a look at the documentation, but my PHP knowledge is extremely limited, so I'm stuggling to figure out how to add the query within the actual dynamic URL. Could I be a bit cheeky and ask you to help me with the actual PHP snippet? – Andrew Oct 13 '21 at 11:14
  • Sorry, not my style :) but try googling for things along the lines of “Wordpress run function on specific page” and I’m confident you can figure it out! – Leland Oct 13 '21 at 12:58
  • It's more the query inside the snippet that I'm struggling with, as opposed to how to run the function on a specific page. Thanks - I'll keep searching. – Andrew Oct 14 '21 at 09:34

1 Answers1

0

This may not be the correct answer to the original query, but proved to be a solid workaround:

Instead of redirecting www.website.com/my-profile to www.website.com/users/john.smith every time it is entered in the URL bar, I created a shortcode that could be used when needed throughout the site.

add_shortcode('bt_redirect_user_link', 'bt_redirect_user_link');
function bt_redirect_user_link ($atts) {
    // check if user is logged in
    if (is_user_logged_in()) {
        // get current user object
        $current_user = wp_get_current_user();
    
        // get user nickname
        $user_nickname = $current_user->data->user_nicename;

        // set the link href
        $link_href = '/users/' . $user_nickname;

        // output the link html
        return $link_href;
    }
}

Fortunately for me, the www.website.com/my-profile link (which needs to be redirected) is only available on buttons/icons visible to logged in users. This may not be a fully workable solution for websites that need to display the link to logged out users, and I assume IF/ELSE statements would needed to be added in those cases.

Andrew
  • 65
  • 5