Redirect a WordPress Post to its Permalink

WordPress
I realize the title of this post may sound a little redundant, but I’ve noticed something peculiar in WordPress, it seems that it will automatically redirect a page if you change the page name (aka slug) but wont bother with anything else in the URL. Case in point I recently published a blog but forgot to set the category name, and my WordPress URLs are set to include the category name as follows http://domain.com/category/slug/ so after I updated the post category I realized the post was still accessible using the old category name in the URL without redirecting, as well as with the new category name, I then noticed I could pretty much type in any category name as long as the slug was right the post would still load, this may be fine or even good from a purely functional stand point but not something you want from an SEO perspective, but luckily you can get the correct permalink and make sure the post redirects there using a couple of built in WordPress functions. Below is the code I placed in the head of my template which makes sure all post direct to the proper permalink.
<?php
//Get the URL used to request the current page.
$pageURL = 'http://'.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
//Get the WordPress permalink.
$pageLink = get_permalink();
//Make sure the page is a single post
if(is_single()){
//Check if the request URL is the same as the WordPress permalink.
if($pageURL!=$pageLink){
//If the URL and permalink are not the same redirect with a 301(permanent) or 302(temporary) redirect
wp_redirect($pageLink, 301);
exit;
}
}
?>






October 6th, 2009 at 8:53 am
Thanks for this information. This will come in handy soon!
Reply