Redirecting a large number of posts to their new WordPress permalinks.

April 25, 2007 by aaron

Add this to the VERY top of your theme’s 404 page.

Change http://localhost/wordpress to your default wordpress folder.

This just does posts and possibly pages that end in the id (with or without the trailing url) Categories etc will have to be done elsewhere or by hand.

< ?php
//Kinda obvious
$rf = $_SERVER[&#039;REQUEST_URI&#039;];
$rf = explode(&#039;/&#039;,$rf);
$last = count($rf);

//Filter out regular 404 that arn&#039;t old urls
if(is_numeric($rf[$last-1])){
    $post_id = $rf[$last-1];
}elseif(is_numeric($rf[$last-2])){
    $post_id = $rf[$last-2];
}

// No sense loading WP if there isn&#039;t an id
if ( $post_id ) {
    // Oh fine we will load wordpress
    define(&#039;WP_USE_THEMES&#039;, false);
    require(&#039;http://localhost/wordpress/wp-blog-header.php&#039;);
        $post = get_post($post_id);
    //Well hope it is the right post. If not, ohwell. We tried.
    if($post){
        //Lets get the new URL
        $new_link = get_permalink($post_id);
        //We don&#039;t want google to get angry with us.
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: $new_link");
    }
}
?>
Categorized as:
comments powered by Disqus