WordPress如何按分类、日期条件筛选标签列表及tag.php归档文章
WordPress 两个筛选需求实现方案
需求1:获取指定分类下、发布日期晚于指定日期的文章关联标签列表
你可以把以下代码放到主题的functions.php文件,或者自定义插件的代码文件中调用:
/** * 获取指定分类下、发布日期晚于指定日期的所有关联标签 * @param int $cat_id 指定分类ID * @param string $date 指定日期 格式示例 '2023-01-01' * @return array 标签对象数组 */ function get_custom_filtered_tags( $cat_id, $date ) { // 先查询符合条件的文章ID,仅返回ID降低性能消耗 $post_ids = get_posts( array( 'category' => $cat_id, 'post_type' => 'post', 'post_status' => 'publish', 'date_query' => array( array( 'after' => $date, 'inclusive' => false, // 不需要包含指定日期当天可设为false ) ), 'posts_per_page' => -1, 'fields' => 'ids', ) ); if ( empty( $post_ids ) ) return array(); // 提取所有符合条件文章的标签ID $tag_ids = array(); foreach ( $post_ids as $pid ) { $post_tags = get_the_tags( $pid ); if ( $post_tags ) { foreach ( $post_tags as $tag ) { $tag_ids[] = $tag->term_id; } } } // 去重后返回完整标签信息 $tag_ids = array_unique( $tag_ids ); return get_terms( array( 'taxonomy' => 'post_tag', 'include' => $tag_ids, 'hide_empty' => true, ) ); }
调用示例:获取分类ID为3、发布日期晚于2022-06-01的标签,写法为$tags = get_custom_filtered_tags( 3, '2022-06-01' );,遍历返回的数组即可输出标签信息。
需求2:tag.php标签归档页过滤指定分类、发布日期早于2020-01-01的文章
使用pre_get_posts钩子修改主查询即可,无需额外自定义循环,性能更优,代码同样放入主题functions.php:
add_action( 'pre_get_posts', 'custom_tag_archive_filter' ); function custom_tag_archive_filter( $query ) { // 仅对前台标签归档页的主查询生效,不影响后台和其他页面查询 if ( ! is_admin() && $query->is_main_query() && is_tag() ) { $query->set( 'cat', 5 ); // 把5替换为你指定的分类ID $query->set( 'date_query', array( array( 'before' => '2020-01-01', 'inclusive' => false, // 需要包含2020-01-01当天可设为true ) ) ); } }
补充说明
- 需要指定多个分类的话,把
$query->set( 'cat', 5 );改为$query->set( 'category__in', array(5,6,7) );,数组内填写你要包含的所有分类ID - 代码生效后tag.php直接使用默认主循环输出文章即可,无需修改原有循环逻辑
内容的提问来源于stack exchange,提问作者Stelios Baglaridis
相关产品推荐
相关产品推荐

