当读者通过WordPress自身的搜索功能来搜索文章时,如果返回的结果只有一篇文章,我们可以直接让它跳转到这篇文章,提高用户体验。
实现的方法很简单,只需要在你主题的 functions.php 文件中添加下面的代码:
add_action('template_redirect', 'redirect_single_post'); function redirect_single_post() { if (is_search()) { global $wp_query; if ($wp_query->post_count == 1 && $wp_query->max_num_pages == 1) { wp_redirect( get_permalink( $wp_query->posts['0']->ID ) ); exit; } } } |
参考资料:http://www.paulund.co.uk/redirect-search-results-return-one-post
来源:
https://www.wpdaxue.com/redirect-search-results-return-one-post.html