wordpress 重定向_当WordPress搜索查询仅返回一个匹配项时自动重定向

wordpress 重定向

There are times when searching a WordPress blog, you only get one item in the result. Depending on how organized your site is, this should be the item the user was looking for anyways. One of our users asked if there was a way to redirect to the post if the search query results only one match. In this article, we are going to show you how to redirect users to the post when the search query only returns one match.

有时搜索WordPress博客时,您只会在结果中得到一项。 根据您网站的组织方式,这应该是用户一直在寻找的项目。 我们的一位用户询问,如果搜索查询结果只有一个匹配项,是否可以重定向到该帖子。 在本文中,我们将向您展示当搜索查询仅返回一个匹配项时,如何将用户重定向到该帖子。

All you have to do is open your theme’s functions.php file and paste the following snippet.

您所要做的就是打开主题的functions.php文件,并粘贴以下代码段。


add_action('template_redirect', 'one_match_redirect');
function one_match_redirect() {
    if (is_search()) {
        global $wp_query;
        if ($wp_query->post_count == 1) {
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
        }
    }
}

Now you must beware that some users will not expect this functionality. So it may freak them out.

现在,您必须提防某些用户不会期望此功能。 因此,可能会吓坏他们。

翻译自: https://www.wpbeginner.com/wp-tutorials/auto-redirect-when-wordpress-search-query-only-returns-one-match/

wordpress 重定向

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值