标签: 输出文章数量

  • WordPress输出文章统计数据的短代码

    WordPress输出文章统计数据的短代码

    将下列代码放入function.php/code snippes也行。

    // 短代码:统计特定文章类型和分类的文章数量
    function custom_post_type_category_count_shortcode($atts) {
        // 提取短代码参数
        $atts = shortcode_atts(
            array(
                'post_type' => 'post',  // 默认文章类型
                'category'  => '',      // 分类的 slug(默认不限制分类)
            ),
            $atts,
            'post_count_category'
        );
    
        // 设置查询参数
        $query_args = array(
            'post_type'      => $atts['post_type'],
            'post_status'    => 'publish',
            'posts_per_page' => -1,
        );
    
        // 如果提供了分类 slug,添加分类查询条件
        if (!empty($atts['category'])) {
            $query_args['category_name'] = $atts['category'];
        }
    
        // 查询文章
        $query = new WP_Query($query_args);
        $count = $query->found_posts;
    
        // 清理查询
        wp_reset_postdata();
    
        // 输出文章数量
        return $count;
    }
    
    // 注册短代码
    add_shortcode('post_count_category', 'custom_post_type_category_count_shortcode');
    

    使用方法

    统计某文章类型的所有文章

    [post_count_category post_type="post"]

    将返回普通文章类型(post)的总数量。

    统计某分类的文章数量

    [post_count_category post_type="post" category="news"]

    将返回分类 news 的已发布文章数量。

    统计某自定义文章类型的特定分类文章数量

    [post_count_category post_type="portfolio" category="design"]

    将返回自定义文章类型 portfolio 且分类为 design 的文章数量。