WordPress 标签页面只有一篇文章时自动跳转到该文章

时间:2022-04-23
本文章向大家介绍WordPress 标签页面只有一篇文章时自动跳转到该文章,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

就Jeff的使用经验的话,我是直接将“标签”作为文章关键词的,这么做也是为了方便代码实现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()) { global $wp_query; if ($wp_query->post_count == 1) { wp_redirect( get_permalink( $wp_query->posts['0']->ID ) ); } } }