如何修改WordPress短码实现按分类和标签筛选自定义文章类型?
修改WordPress资源短码,支持分类+标签联合筛选
原短码仅能按分类筛选自定义文章类型resource,现在调整为同时支持分类和标签筛选,比如使用[Resources category="videos" tags="ministry, devotions"],就能只展示分类为videos且带有ministry、devotions标签的内容。
直接看修改后的完整代码:
add_shortcode( 'Resources', 'resources' ); function resources( $atts, $shrt_content = null ) { // 初始化短码参数,新增tags属性 $atts = shortcode_atts(array( 'category' => '', 'tags' => '' ), $atts, ''); // 处理分类参数,拆分成数组并去除空格 $categories = !empty( $atts['category'] ) ? array_map('trim', explode( ',' , $atts['category'] )) : array(); // 处理标签参数,拆分成数组并去除空格 $tags = !empty( $atts['tags'] ) ? array_map('trim', explode( ',' , $atts['tags'] )) : array(); $args = array( 'post_type' => 'resource', 'post_status' => 'publish', 'orderby' => 'title', 'order' => 'ASC', 'posts_per_page' => -1 ); // 构建分类和标签的联合查询条件 $tax_query = array(); if ( !empty($categories) ) { $tax_query[] = array( 'taxonomy' => 'category', 'field' => 'slug', 'operator' => 'AND', 'terms' => $categories ); } if ( !empty($tags) ) { $tax_query[] = array( 'taxonomy' => 'post_tag', // 若使用自定义标签分类法,替换为对应slug即可 'field' => 'slug', 'operator' => 'AND', 'terms' => $tags ); } // 仅当有查询条件时,才将tax_query加入参数 if ( !empty($tax_query) ) { $args['tax_query'] = $tax_query; // 默认tax_query多条件为AND关系,刚好满足"分类+标签同时匹配"的需求 } $post_query = new WP_Query( $args ); ob_start(); if ( $post_query->have_posts() ) { ?> <?php while ( $post_query->have_posts() ) : $post_query->the_post(); ?> <p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><?php if(get_field('short_description')) { echo ' - ' . get_field('short_description') . ''; } ?></p> <?php endwhile; ?> <?php wp_reset_postdata(); // 用wp_reset_postdata替代wp_reset_query,更符合自定义WP_Query的规范 ?> <?php } $retVal = ob_get_contents(); ob_end_clean(); return $retVal; }
关键调整说明:
- 新增
tags短码参数,支持逗号分隔多个标签值 - 处理参数时用
array_map('trim', ...)去除每个值前后的空格,避免用户输入空格导致筛选失效 - 重构
tax_query构建逻辑:仅当存在分类或标签条件时才添加查询,避免空条件引发WP_Query错误 - 将
wp_reset_query()替换为wp_reset_postdata(),适配自定义WP_Query的场景
现在这个短码支持三种使用场景:
[Resources category="books, videos"]:仅按分类筛选[Resources tags="ministry, devotions"]:仅按标签筛选[Resources category="videos" tags="ministry, devotions"]:同时满足分类和标签的内容才会显示
内容的提问来源于stack exchange,提问作者mwgideon
相关产品推荐
相关产品推荐

