Skip to content

Instantly share code, notes, and snippets.

@ryanshoover
Last active February 14, 2017 17:39
Show Gist options
  • Save ryanshoover/f2a8de7471b36e23c47781b819bba149 to your computer and use it in GitHub Desktop.
Save ryanshoover/f2a8de7471b36e23c47781b819bba149 to your computer and use it in GitHub Desktop.
WordPress - Redirect 404s that end in a post's name
<?php
/**
* Plugin Name: Rowley Redirect
* Description: Redirect old links for posts to the current link
* Author: Ryan Hoover
* Author URI: https://github.com/ryanshoover
* Version: 0.1
*/
/**
* Redirect 404s that end in the post name
*
* If a request comes in that is a 404, but the last
* subdirectory is a post's slug, then redirect to
* that post's actual link
*/
function rowley_redirect_category_post_links() {
// If this isn't a 404 error page, abort
if ( 404 != get_query_var( 'error' ) ) {
return;
}
// Get the request path's parts
$request_parts = explode( '/', $_SERVER['REQUEST_URI'] );
$request_parts = array_filter( $request_parts );
// If we don't have any parts, abort
if ( empty( $request_parts ) ) {
return;
}
// Find the post that has the matching slug
$post_slug = array_pop( $request_parts );
$post = get_page_by_path( $post_slug, null, 'post' );
// If we didn't find a post, abort
if ( empty( $post ) ) {
return;
}
// Redirect to the post's actual link
wp_safe_redirect( get_permalink( $post->ID ) );
exit;
}
add_action( 'wp', 'rowley_redirect_category_post_links' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment