Hack: Redirect Posts To Any URL

Suppose you have an old post that you want to remove, but you know there are still links to it out there. Ideally you want to redirect anyone coming to that page to another page on your site, or maybe even to another site. You can do that with a few lines of code, and in such a way that you can customize the destination URL on a post-by-post basis without touching the code again. So no need for a plugin or messing with your .htaccess file.

By using the template_redirect action, you can stop the page from loading at the right moment, and instead do a proper redirect using wp_redirect. I’m using a custom field called redirecturl. If the field is present for the page or post, it will do the redirect. Otherwise, nothing special happens.

function wpaction_template_redirect() {
	$redirecturl = get_post_meta(get_the_ID(),'redirecturl',true);
	if (strlen($redirecturl) > 0) {

So once you have this added to your functions.php or custom plugin, you can just add the redirecturl field to any post where you want to have the redirect.

Leave a Reply

Your email address will not be published. Required fields are marked *