Skip to content

Instantly share code, notes, and snippets.

@scottnelle
Created January 12, 2016 22:20
Show Gist options
  • Save scottnelle/90260a73420bd3176ff5 to your computer and use it in GitHub Desktop.
Save scottnelle/90260a73420bd3176ff5 to your computer and use it in GitHub Desktop.
Redirect legacy urls to WordPress posts. Assumes that the legacy URL was stored to post meta as legacy_url during migration.
<?php
function redirect_legacy_urls() {
if ( ! is_404() ) {
return;
}
$url = trim( parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ), '/' );
if ( empty( $url ) ) {
return false;
}
// this is a slow query. consider caching as a transient. use a hashed version of the url as the key.
$query = new WP_Query( array(
'posts_per_page' => 1,
'meta_query' => array(
array(
'key' => 'legacy_url',
'value' => $url,
'compare' => 'LIKE',
),
),
'no_found_rows' => true,
'update_post_term_cache' => false,
) );
if ( $query->have_posts() ) {
wp_safe_redirect( get_permalink( $query->posts[0]->ID ), 301 );
exit;
}
}
add_action( 'template_redirect', 'redirect_legacy_urls', 100 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment