You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress归档页面自定义分类法文章数量短码适配问题

解决自定义分类法归档页短码自动显示产品总数的问题

问题说明

现有短码[category_product_count]可通过指定id参数显示product_cat分类下的产品总数,但在product_cat归档页面不传入id时无法正常工作,需要实现短码在归档页自动识别当前分类并显示对应产品数。

修改后代码

function category_product_count_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'id' => '',
    ), $atts );

    // 初始化分类对象
    $category = null;

    // 处理传入ID的情况
    if ( ! empty( $atts['id'] ) ) {
        $category = get_term( $atts['id'], 'product_cat' );
    } 
    // 归档页自动获取当前分类
    elseif ( is_tax( 'product_cat' ) ) {
        $category = get_queried_object();
    }

    // 验证分类有效性
    if ( ! $category || is_wp_error( $category ) ) {
        return '0';
    }

    // 直接使用分类内置的count属性,无需额外查询
    return $category->count;
}
add_shortcode( 'category_product_count', 'category_product_count_shortcode' );

关键修改点

  • 自动识别归档页分类:通过is_tax('product_cat')判断是否处于product_cat分类归档页面,是的话用get_queried_object()获取当前分类对象
  • 优化计数方式:放弃原代码中WP_Query的查询方式,直接调用分类对象的count属性,该值由WordPress维护,性能更优
  • 增加错误处理:当传入ID无效或未识别到分类时,返回0避免页面报错

使用方式

  • 指定分类ID调用:[category_product_count id="12"]
  • 归档页直接调用:[category_product_count](自动显示当前分类的产品总数)

内容的提问来源于stack exchange,提问作者Cosmin Dan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 03:07:12