Skip to content

Instantly share code, notes, and snippets.

@kierzniak
Created February 28, 2018 10:02
Show Gist options
  • Save kierzniak/51001ce15b5c594da2cffc720c080a23 to your computer and use it in GitHub Desktop.
Save kierzniak/51001ce15b5c594da2cffc720c080a23 to your computer and use it in GitHub Desktop.
Redirect posts with old permalink structure to new links.
<?php
/**
* Redirect posts with old permalink structure to new links.
*
* If you change your posts permalink structure you should redirect all
* trafic from old permalink to new one. This script will redirect posts
* from /%postname%/ to current post link using 301 status.
*
* This script is working only for /%postname%/ => current link
*
* @param $query WP Current WordPress environment instance
*
* @return WP
*/
function motivast_redirect_old_post_permalink_structure( $query ) {
/**
* If there is no 404 error do nothing
*/
if( !isset($query->query_vars) || !isset( $query->query_vars['error'] ) || $query->query_vars['error'] !== '404' ) {
return $query;
}
/**
* Query request will be post slug
*/
$slug = $query->request;
/**
* Search for the post with slug from query
*/
$post_query = new WP_Query(array(
'post_type' => 'post',
'name' => $slug,
'posts_per_page' => 1,
));
/**
* If there is post with such a slug we can redirect user with 301
* status to new link.
*/
if( $post_query->have_posts() ) {
$post = current($post_query->posts);
$link = get_permalink($post->ID);
wp_safe_redirect( $link, 301 );
exit;
}
return $query;
}
add_filter( 'parse_request', 'motivast_redirect_old_post_permalink_structure' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment