當你的讀者在你的 WordPress 博客的內置的搜索引擎搜索時候,返回的結果是按照時間先後的陳列格式。如果搜索結果只有一篇文章的時候,為提高用户體驗,我們可以讓着唯一的一個搜索結果自動跳轉到該文章。下面就是所需要的代碼。

將下面的代碼添加到主題的 funtions.php 文件的最後一個 ?> 前:

  1. //搜索結果自動跳轉 Devework.com
  2. add_action('template_redirect', 'redirect_single_post');
  3. function redirect_single_post() {
  4.     if (is_search()) {
  5.         global $wp_query;
  6.         if ($wp_query->post_count == 1) {
  7.             wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
  8.         }
  9.     }
  10. }