最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

functions - 404 redirect to previous category

programmeradmin4浏览0评论

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' );
发布评论

评论列表(0)

  1. 暂无评论