SEO小技巧:如何重定向404页面到搜索页

404页面对用户来说是不友好的页面。而目前常规的做法是是在404页面增加一个搜索表单。这样也同样不友好,我们推荐下面的方法来将404页面重定向到搜索页并自动填写搜索关键字。如下图。

Auto Redirect 404 To Search Page

使用下面的代码,它将每个404响应重定向到搜索页面,并显示URL中的默认结果。 它使访问者可以找到自己想要的东西,而不必强制重定向到他不想要的页面。

function page_404_to_search_page() {
global $wp_query;
if( is_404() ) {
$s = $wp_query->query['name'];
$search = preg_replace("/[^a-zA-Z0-9]+/", " ", $s);
$url_to = "/?s=" . $search; 
wp_safe_redirect( $url_to );
exit;
}
}
add_action( 'template_redirect', 'page_404_to_search_page' );

把上面的代码放在您主题的funtions.php里面即可。无需任何设置或是其它操作。

本文已在Ie主题99839发布

文章来源:https://ietheme.com/auto-404-to-search.html


撰写评论

您的邮箱地址不会被公开。 必填项已用 * 标注

加入我们

注册完成!

密码重置

请输入您的邮箱地址。 您将收到一个链接来创建新密码。

检查你的邮件中的确认链接。


Fatal error: Uncaught Error: Call to undefined function fnmatch() in /www/wwwroot/ietheme.com/wp-content/plugins/object-cache-pro/src/ObjectCaches/ObjectCache.php:426 Stack trace: #0 /www/wwwroot/ietheme.com/wp-content/plugins/object-cache-pro/src/ObjectCaches/ObjectCache.php(405): RedisCachePro\ObjectCaches\ObjectCache->isNonPrefetchableGroup() #1 /www/wwwroot/ietheme.com/wp-content/plugins/object-cache-pro/src/ObjectCaches/Concerns/PrefetchesKeys.php(139): RedisCachePro\ObjectCaches\ObjectCache->isPrefetchableGroup() #2 [internal function]: RedisCachePro\ObjectCaches\PhpRedisObjectCache->RedisCachePro\ObjectCaches\Concerns\{closure}() #3 /www/wwwroot/ietheme.com/wp-content/plugins/object-cache-pro/src/ObjectCaches/Concerns/PrefetchesKeys.php(138): array_filter() #4 /www/wwwroot/ietheme.com/wp-content/plugins/object-cache-pro/src/ObjectCaches/PhpRedisObjectCache.php(206): RedisCachePro\ObjectCaches\PhpRedisObjectCache->storePrefetches() #5 [internal function]: RedisCachePro\ObjectCaches\PhpRedisObjectCache->close() #6 {main} thrown in /www/wwwroot/ietheme.com/wp-content/plugins/object-cache-pro/src/ObjectCaches/ObjectCache.php on line 426