WORDPRESS SIMPLE REDIRECT
Recently I needed an easy way for a client to create a link in a WordPress powered website that would automagically redirect a visitor to a certain location upon visiting. Part of the requirement was that this link could be easily remembered and used in printed material such as leaflets and magazines. As an extra option it should be easy to change the location towards the redirection would point. I couldn’t find anything like this so I created a very simple little page template.
How it works:
Copy the template page Page Redirect code below to a file and save it as page-redirect.php in your own template’s directory. Create a Page in WordPress and set the Page’s template to Page Redirect. Add a custom field to this page with the name redirect_url and the full url of the url you want to redirect to.
For instance: http://www.redirected-location.com. Now save the page and you should now test it by visiting the page you created.
For example (I assume you are using nice urls):
http://www.your-website.com/the-page-title-of-the-page-with-the-redirect-template
If all went well you should be instantaneously be redirected (using a standard php redirect with a 302 HTTP redirect) ) to the url you entered in the custom field. You can easily change the redirect location by changing the value of the custom field.
Code:
< ?php
/*
* Template Name: Page Redirect
*
* Makes it easy to redirect a page to another url, using the parameter redirect_url
*/
$redirect_url = get_post_meta($post->ID, "redirect_url", true);
// Defaults if no options we're given
if( ! empty($redirect_url) ) { header("Location: $redirect_url"); } else { echo ""; }
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
As I said it uses the standard PHP redirect, but you could easily change or extend it with more specific http headers if needs arise. Feel free to use the above snippet as you see fit, as far as I’m concerned it’s in the public domain. I hope this might be useful to you. If you have any questions, feel free to leave a comment.
