我是直接将 「标签」 作为文章关键词的,这么做也是为了方便代码实现 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.     }