Last active
September 22, 2021 16:36
-
-
Save wpscholar/d37736b1b9c2439acf2289364e210bc5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Plugin Name: Auto-Redirect Root-Level Posts | |
* Plugin URI: https://gist.github.com/wpscholar/d37736b1b9c2439acf2289364e210bc5 | |
* Description: Automatically redirects root level posts (e.g. /my-blog-post) to the new location (e.g. /blog/my-blog-post). Use anytime you update your post permalink structure from root-level to use a subdirectory prefix. | |
* Version: 1.0 | |
* Author: Micah Wood | |
* Author URI: https://wpscholar.com | |
* License: GPL2 | |
* License URI: https://www.gnu.org/licenses/gpl-2.0.html | |
*/ | |
add_action( 'template_redirect', function () { | |
/** | |
* @var WP $wp | |
*/ | |
global $wp; | |
/** | |
* @var WP_Query $wp_query | |
*/ | |
global $wp_query; | |
if ( $wp_query->is_404() ) { | |
$query = new WP_Query( array( | |
'post_type' => 'post', | |
'post_status' => 'publish', | |
'name' => $wp->request, | |
'posts_per_page' => 1, | |
'nopaging' => true, | |
'no_found_rows' => true, | |
) ); | |
if ( $query->post_count === 1 ) { | |
$redirect_url = add_query_arg( $wp->query_string, '', get_the_permalink( $query->post ) ); | |
wp_safe_redirect( $redirect_url, 301 ); | |
} | |
} | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment