Skip to content

Instantly share code, notes, and snippets.

@webdados
Last active January 21, 2017 13:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webdados/c868cb559d36814d429d12e2d0ceb440 to your computer and use it in GitHub Desktop.
Save webdados/c868cb559d36814d429d12e2d0ceb440 to your computer and use it in GitHub Desktop.
<?php
/*
* When migrating an old website to WordPress, you should store pages/posts/... URLs in a custom field
* Example: /studio.php
* You can create a metabox to manually insert the URL, on the post edit scree, or have it imported directly if you are exporting/importing from the old CMS to WordPress
* If some visitor lands on the old URL, you then hook into the template_redirect, check if it's a 404, and then try to redirect him to the correct page/post/...
* This is of extreme importance SEO wise
*/
add_action( 'template_redirect', 'old_urls_redirect' );
function old_urls_redirect() {
if ( is_404() ) {
global $wpdb;
//Replace meta_key with your custom field name
$post_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM ".$wpdb->postmeta." WHERE meta_key='ma-404-301-old-url' AND meta_value = %s", trim( $_SERVER['REQUEST_URI'] ) ) );
if ( $post_id ) {
//Redirect if a post is found
wp_redirect( get_permalink($post_id), 301 );
} else {
//No post found - Maybe it's an URL that do not map directly to post (Thanks Mike Schinkel)
//I'm using an array, but we could use any other method, for example, a CPT with two custom fields "old_url" / "new_url"
$url_mapping = array(
//'old_url' => 'new_url',
)
if ( isset( $url_mapping[ trim( $_SERVER['REQUEST_URI'] ) ] ) && trim( $url_mapping[ trim( $_SERVER['REQUEST_URI'] ) ] ) != '' ) {
wp_redirect( trim( $url_mapping[ trim( $_SERVER['REQUEST_URI'] ) ] ), 301 );
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment