如何通过短代码动态显示自定义文章类型分类法的文章数量
实现自定义分类法下文章数量的短代码
以下是适配你需求的短代码实现,可动态统计指定自定义分类法下的文章数量,支持自动识别当前归档页分类或手动指定分类:
代码实现
将以下代码添加到你的WordPress主题functions.php文件或自定义功能插件中:
function ai_tool_category_count_shortcode( $atts ) { // 设置默认参数,匹配你的自定义类型和分类法 $atts = shortcode_atts( array( 'taxonomy' => 'best-ai-tools', 'post_type' => 'AI-Tools', 'category' => '' ), $atts ); $term_id = 0; // 自动获取当前归档页的分类ID if ( empty( $atts['category'] ) && is_tax( $atts['taxonomy'] ) ) { $current_term = get_queried_object(); $term_id = $current_term->term_id; } // 根据指定的分类slug获取ID elseif ( !empty( $atts['category'] ) ) { $term = get_term_by( 'slug', $atts['category'], $atts['taxonomy'] ); if ( $term && !is_wp_error( $term ) ) { $term_id = $term->term_id; } } if ( $term_id === 0 ) { return '0'; } // 精准统计已发布的目标文章类型数量 $query_args = array( 'post_type' => $atts['post_type'], 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => $atts['taxonomy'], 'field' => 'term_id', 'terms' => $term_id ) ), 'posts_per_page' => -1, 'fields' => 'ids' // 仅获取ID,提升查询性能 ); $post_query = new WP_Query( $query_args ); return $post_query->found_posts; } add_shortcode( 'ai_category_count', 'ai_tool_category_count_shortcode' );
使用方式
1. 归档页自动显示当前分类文章数
在Elementor的短代码模块或文本模块中插入:[ai_category_count]
短代码会自动识别当前best-ai-tools分类归档页的分类,统计对应AI-Tools类型的已发布文章数量。
2. 指定特定分类显示数量
如果需要在任意页面展示某个分类的文章数,传入分类slug即可:[ai_category_count category="your-category-slug"]
例如,分类slug为ai-image-generators时,使用:[ai_category_count category="ai-image-generators"]
3. 复用短代码到其他类型/分类法
若后续需要统计其他自定义文章类型或分类法,可指定对应参数:[ai_category_count taxonomy="other-taxonomy" post_type="other-post-type" category="target-category"]
注意事项
- 确保自定义文章类型
AI-Tools和分类法best-ai-tools的slug拼写完全匹配,WordPress对slug大小写敏感。 - 建议将代码添加到自定义功能插件中,避免主题更新后代码丢失。
- 代码采用
WP_Query统计已发布状态的文章,比直接调用分类元数据的计数更准确,排除了草稿、待审核等非公开状态的内容。
内容的提问来源于stack exchange,提问作者Cosmin Dan
相关产品推荐
相关产品推荐

