admin管理员组

文章数量:1334337

Hi I'm looking for code that I can place in my theme's functions.php that will redirect 404 pages to the previously viewed category.

For example:

If www.example/category1/item-name goes to a 404, then redirect to www.example/category1/

Edited:

Think I found it:

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' );

本文标签: functions404 redirect to previous category