我是直接將 「標籤」 作為文章關鍵詞的,這麼做也是為了方便代碼實現 WordPress 自動關鍵詞 keywords 與描述 description 。但如此常常是一個 「標籤」 才對應一篇文章,為了提高用户體驗,我們可以在 WordPress 標籤頁面只有一篇文章時自動跳轉到該文章。
將下面的代碼添加到主題的 functions.php 文件下:
- add_action('template_redirect', 'tag_redirect_single_post');
- function tag_redirect_single_post() {
- if (is_tag()) {
- global $wp_query;
- if ($wp_query->post_count == 1) {
- wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
- }
- }
- }
代碼作者未知。高級一點的,可以將此與 《WordPress 內置搜索結果只有一篇文章時自動跳轉到該文章》 一文的代碼合併為如下:
- add_action('template_redirect', 'redirect_single_post');
- function redirect_single_post() {
- if (is_tag() || is_search()) {
- gl
obal $wp_query; - if ($wp_query->post_count == 1) {
- wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
- }
- }