Skip to content

Instantly share code, notes, and snippets.

@kopepasah
Created January 13, 2017 06:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kopepasah/8017f8ccf5681570de5ce14fff6248be to your computer and use it in GitHub Desktop.
Save kopepasah/8017f8ccf5681570de5ce14fff6248be to your computer and use it in GitHub Desktop.
Simple redirect function to correctly redirect lost posts.
<?php
/**
* Redirect Lost Posts
*
* @author Justin Kopepasah <justin@kopepasah.com>
* @license MIT
*/
add_action( 'template_redirect', function() {
// Only redirect if nothing is found.
if ( is_404() ) {
$post = get_page_by_path( $_SERVER['REQUEST_URI'], OBJECT, 'post' );
// Only redirect if a post is found using the URI.
if ( null !== $post ) {
wp_safe_redirect( get_permalink( $post->ID ), 301 );
exit();
}
}
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment