We can redirect website visitor to another url in wordpress using wp_redirect() function.
wp_redirect()
This function redirects the user to a specified url. To use this function edit your page template and specify the function at the top as per following syntax:
1 2 3 4 5 6 7 | <?php wp_redirect( $location-url, $status ); exit; ?> |
This wordpress function takes 2 parameters :
- $location-url (required) : url to redirect where you want to redirect visitors to. It’s required to specify. It can be internal or external link.
- $status (optional) : status code to use. Default is 302. This parameter specifies the type of redirect. (see all http status codes at wikipedia)
for example if you want visitors to move from an old page to a new one as well as permanent redirection to make Google to transfer your page rank & inbound link to the new page, your status code will be 301.
Note:
- wp_redirect() does not exit automatically and so always follow it by “exit” keyword.
- Always call this function before any output is sent to the browser otherwise you will likely get a “headers already sent” error.
Examples :
1 2 3 4 5 6 7 8 9 10 11 | <?php wp_redirect( 'https://fellowtuts.com', 301 ); exit; ?> or <?php wp_redirect( home_url()); exit; ?> |
That’s it. Now you can easily use the safer WordPress function instead of the old php header method.
Keep continue to visit our website fellowtuts.com. We will describe more methods for redirection and to get rid from the error “headers already sent” in our upcoming articles.
Nice tutorial. I’ve read a bunch of tuts on this wp_redirect() function and the wp_redirect hook, but they are all — including this one — incomplete. None of them explain how or where to indicate to WordPress what “original” URL that visitors may be trying to navigate to, that you will be redirecting from. Additionally, modern (2018) methods say this code should go in your “functions.php” file.