WordPress获取指定文章类型文章数量完全指南

本文介绍了在WordPress中统计文章数量的多种方法。核心是使用wp_count_posts()函数获取指定文章类型和状态的数量。文章提供了基础函数、带缓存的优化函数以及批量获取函数,并展示了在主题中显示、后台菜单添加统计和创建短代码等实际应用示例,以提高网站性能和开发效率。

文章作者:曾凤祥
阅读时间: 26 分钟
更新时间:2026年4月15日

一、核心方法

1.1 使用 wp_count_posts() 函数

// 获取已发布的文章数量
$post_counts = wp_count_posts('post'); // 文章
echo '已发布文章: ' . $post_counts->publish;

$product_counts = wp_count_posts('product'); // 产品
echo '已发布产品: ' . $product_counts->publish;

// 获取所有状态的数量
$total_posts = $post_counts->publish + $post_counts->draft + $post_counts->pending;

1.2 获取指定状态的数量函数

function get_post_count($post_type = 'post', $status = 'publish') {
    $counts = wp_count_posts($post_type);
    return isset($counts->$status) ? $counts->$status : 0;
}

// 使用示例
$published_products = get_post_count('product', 'publish');
$draft_posts = get_post_count('post', 'draft');

二、实用快捷函数

2.1 带缓存的获取函数

// 带缓存的获取函数
function get_cached_post_count($post_type, $status = 'publish') {
    $cache_key = "post_count_{$post_type}_{$status}";
    $count = wp_cache_get($cache_key, 'post_counts');
    
    if ($count === false) {
        $counts = wp_count_posts($post_type);
        $count = isset($counts->$status) ? $counts->$status : 0;
        wp_cache_set($cache_key, $count, 'post_counts', 3600); // 缓存1小时
    }
    
    return $count;
}

2.2 批量获取函数

// 批量获取多个文章类型的数量
function get_bulk_post_counts($post_types, $status = 'publish') {
    $results = [];
    
    foreach ($post_types as $type) {
        $results[$type] = get_post_count($type, $status);
    }
    
    return $results;
}

// 使用示例
$counts = get_bulk_post_counts(['post', 'page', 'product'], 'publish');
echo "文章: {$counts['post']}, 页面: {$counts['page']}, 产品: {$counts['product']}";

三、实际应用示例

3.1 在主题中显示文章数量

// 在主题文件中使用
<div class="post-stats">
    <h3>网站内容统计</h3>
    <ul>
        <li>文章: <?php echo get_post_count('post', 'publish'); ?>篇</li>
        <li>产品: <?php echo get_post_count('product', 'publish'); ?>个</li>
        <li>页面: <?php echo get_post_count('page', 'publish'); ?>页</li>
    </ul>
</div>

3.2 后台管理菜单添加统计

// 在functions.php中添加
add_filter('admin_menu', 'add_post_count_to_menu');

function add_post_count_to_menu() {
    global $menu;
    
    // 为文章菜单添加数量
    $post_count = get_post_count('post', 'publish');
    foreach ($menu as $key => $item) {
        if ($item[2] == 'edit.php') {
            $menu[$key][0] .= " <span class='update-plugins count-{$post_count}'><span class='plugin-count'>{$post_count}</span></span>";
        }
    }
}

3.3 创建短代码

// 创建短代码 [post_count type="post" status="publish"]
add_shortcode('post_count', 'post_count_shortcode');

function post_count_shortcode($atts) {
    $atts = shortcode_atts([
        'type' => 'post',
        'status' => 'publish',
        'label' => 'true'
    ], $atts);
    
    $count = get_post_count($atts['type'], $atts['status']);
    $output = $count;
    
    if ($atts['label'] === 'true') {
        $post_type_obj = get_post_type_object($atts['type']);
        $type_name = $post_type_obj ? $post_type_obj->labels->name : $atts['type'];
        $output = "{$type_name}: {$count}";
    }
    
    return $output;
}

// 使用示例
// [post_count type="product"]  // 显示产品数量
// [post_count type="post" status="draft"]  // 显示草稿数量

四、高级优化技巧

4.1 自定义数据库查询(性能最好)

function get_post_count_fast($post_type, $status = 'publish') {
    global $wpdb;
    
    $query = $wpdb->prepare(
        "SELECT COUNT(*) FROM {$wpdb->posts} 
         WHERE post_type = %s AND post_status = %s",
        $post_type,
        $status
    );
    
    return (int) $wpdb->get_var($query);
}

4.2 清除缓存时机

// 在文章发布/删除时清除缓存
add_action('save_post', 'clear_post_count_cache');
add_action('delete_post', 'clear_post_count_cache');

function clear_post_count_cache($post_id) {
    $post_type = get_post_type($post_id);
    wp_cache_delete("post_count_{$post_type}_publish", 'post_counts');
    wp_cache_delete("post_count_{$post_type}_draft", 'post_counts');
}

五、使用示例汇总

5.1 基本使用

// 获取各种文章类型数量
$posts_count = get_post_count('post');  // 默认获取已发布的
$draft_posts = get_post_count('post', 'draft');
$products_count = get_post_count('product');
$pages_count = get_post_count('page');

5.2 在循环中显示

// 在文章循环中显示分类文章数量
if (have_posts()) {
    while (have_posts()) {
        the_post();
        $categories = get_the_category();
        foreach ($categories as $category) {
            $count = get_category_post_count($category->term_id);
            echo "{$category->name} ({$count}篇文章)";
        }
    }
}

function get_category_post_count($category_id) {
    $args = [
        'category__in' => [$category_id],
        'post_status' => 'publish',
        'posts_per_page' => 1,
        'fields' => 'ids',
        'no_found_rows' => false,
    ];
    
    $query = new WP_Query($args);
    return $query->found_posts;
}

六、注意事项

  1. 性能:频繁调用时使用缓存版本
  2. 权限:确保用户有权限查看数据
  3. 准确性:考虑文章状态(publish、draft、pending等)
  4. 多站点:在多站点环境下使用 switch_to_blog()切换

七、一句话解决方案

// 最简单的方法
$count = wp_count_posts('your_post_type')->publish;

// 带缓存的简单方法
$count = get_cached_post_count('your_post_type', 'publish');

选择方法的原则:

大量统计用自定义查询

简单需求用 wp_count_posts()

频繁调用用缓存版本

这篇文章有用吗?

点击星号为它评分!

平均评分 0 / 5. 投票数: 0

到目前为止还没有投票!成为第一位评论此文章。

在AI工具中继续讨论:

曾凤祥

曾凤祥

WordPress技术负责人
小兽WordPress凭借15年的WordPress企业网站开发经验,坚持以“为企业而生的WordPress服务”为宗旨,累计为10万多家客户提供高品质WordPress建站服务,得到了客户的一致好评。我们一直用心对待每一个客户,我们坚信:“善待客户,将会成为终身客户”。小兽WordPress能坚持多年,是因为我们一直诚信。

相关文章

无论你是否已有网站,我们都能帮你把线上业务推上新高度

从0到1,快速搭建专业线上业务平台

从0到1,快速搭建专业线上业务平台

无论您从事何种行业,小兽WordPress​ 都能为您提供专业、可定制、易维护的网站构建方案。我们精选多款高品质模板,适用于展示型官网、品牌形象站、外贸独立站等多种场景,助您快速上线,抢占市场先机。无需代码,轻松启动,即享专业设计。

立即查看所有模版
已有网站?我们来帮你加速、优化、变现

已有网站?我们来帮你加速、优化、变现

您的网站是否遇到加载慢、跳出率高、SEO停滞、体验老旧等问题?这不仅影响技术表现,更会导致客户流失与增长瓶颈。小兽WordPress​ 为您提供全面诊断、提速优化与价值深耕服务,通过“技术+策略”双驱动,助力网站高效转化,推动业务持续增长。

马上获取专属优化方案
微信联系
chat 扫码联系
模板建站
挑选模板
网站定制
免费诊断
咨询热线
咨询热线

189-0733-7671

返回顶部