當讀者通過WordPress自身的搜索功能來搜索文章時,如果返回的結果隻有一篇文章,我們可以直接讓它跳轉到這篇文章,提高用戶體驗。
實現的方法很簡單,隻需要在你主題的 functions.php 文件中添加下面的代碼:
1 2 3 4 5 6 7 8 9 10 |
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; } } } |
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