我是直接將 「標籤」 作為文章關鍵詞的,這麼做也是為了方便程式碼實現 WordPress 自動關鍵詞 keywords 與描述 description 。但如此常常是一個 「標籤」 才對應一篇文章,為了提高使用者體驗,我們可以在 WordPress 標籤頁面只有一篇文章時自動跳轉到該文章。

將下面的程式碼新增到主題的 functions.php 檔案下:

  1. add_action('template_redirect', 'tag_redirect_single_post');
  2. function tag_redirect_single_post() {
  3.     if (is_tag()) {
  4.         global $wp_query;
  5.         if ($wp_query->post_count == 1) {
  6.             wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
  7.         }
  8.     }
  9. }

程式碼作者未知。高階一點的,可以將此與 《WordPress 內建搜尋結果只有一篇文章時自動跳轉到該文章》 一文的程式碼合併為如下:

  1. add_action('template_redirect', 'redirect_single_post');
  2. function redirect_single_post() {
  3. if (is_tag() || is_search()) {
  4.         gl
    obal
     $wp_query;
  5.         if ($wp_query->post_count == 1) {
  6.             wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
  7.         }
  8.     }