Redirect "dumb" URL to Author's custom post

98 Views Asked by At

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!

1

There are 1 best solutions below

0
On

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.