Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End How to create wildcard redirects using wp_redirect

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #234695
    Ayanize
    Participant

    Hope I am getting the question right and understandable.

    I am using bbpress which is creating the profile like this domain.com/forums/user/my-username and of course the URL changes with some other user.

    Now, I want to implement a redirect for such URLs to another page. Not sure how I will do this using wp_redirect.

    add_action ('init' , 'redirect_edit_user_link');
    
    function redirect_edit_user_link(){         
            if (strpos ($_SERVER ['REQUEST_URI'] , '/forums/user' ) && current_user_can('publish_posts')) {
                wp_redirect ("/developers/");
                exit;
             }
    
    }
    
    #234696
    Alen
    Participant

    @klmnweb I’ve tested following locally and it works. I didn’t have bbpress installed but I replicated the URL structure by creating sub pages. /forums/, /forums/user and /forums/user/jamie

    add_action('init','redirect_edit_user_link');
    
    function redirect_edit_user_link() {
        if ( current_user_can('publish_posts') ) {
            if ( strpos($_SERVER['REQUEST_URI'], '/forums/user/') !== false ) {
                wp_redirect('/developers');
                exit;
            }
        }
    }
    

    While above code works, I would still make the redirect at server level. Why bother processing PHP. Following will redirect ex: /forums/user/adam to /developers/adam.

    # Apache
    RedirectMatch 301 /forums/user/(.*) /developers/$1
    
    # Nginx
    location ~ /forums/user/(.*) {
        rewrite ^(.*)$ /developers/$1 redirect;
    }
    

    Hope that helps, Alen.

    #234698
    Ayanize
    Participant

    @Alen.. Thanks a lot.. You’re really a gem. I took the php way because I had some conditions for the redirect as you can. I wanted a specific user (in my site one custom role of shop_vendors) who has limited capabilities on the site but has also access to forums be redirected to a custom made profile page. And that’s why I was looking for the wp_redirect function. Your function worked very well. I just made one more addition to the condition and it worked like a charm.

    Thank you once again.

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘Back End’ is closed to new topics and replies.