Wordpress

Redirect 404 to Parent Post in WordPress

This method is very useful especially when you have migrate your post/attachment permalinks. In my case i use this redirection method when my image attachments got renamed using  Media File Renamer by Jordy Meow and causing my visitors stopped at 404 pages when they visited image attachment links from search engine (google). Using this script will redirect the visitors of your 404 post/image attachments to its  parent post (if any) or to your homepage.

add this following lines to your theme functions.php :

function __404_template_redirect()
{
    if( is_404() )
    {
        $req = $_SERVER['REQUEST_URI'];

        if ( is_file( $req )) {
            return; // don't reduce perf by redirecting files to home url
        }

        // pull the parent directory and convert to site url
        $base_dir = dirname( $req );
        $parent_url = site_url( $base_dir );

        // redirect to parent directory
        wp_redirect( $parent_url, 301 );
        exit();
    }
}

add_action( 'template_redirect', '__404_template_redirect' );

Leave a Reply