wp_count_posts() 是 WordPress 內建的高效統計函數,能快速獲取各狀態(已發布、草稿、定時、垃圾桶等)的文章數量。支援所有文章類型(Post、Page、自訂 CPT),並提供快取機制,效能遠優於自行撰寫 SQL 查詢。本文將詳細說明參數、回傳結構、常見用法與進階技巧。
wp_count_posts( string $type = 'post', string $perm = '' ): stdClass
| 參數 | 類型 | 預設值 | 說明 |
|---|---|---|---|
$type | string | 'post' | 文章類型 slug,如 'post'、'page' 或自訂 CPT 名稱 |
$perm | string | '' | 設為 'readable' 時,將私密文章納入統計(需用戶有讀取權限) |
函數回傳 stdClass 物件,屬性對應文章狀態:
stdClass Object
(
[publish] => 123 // 已發布
[future] => 5 // 定時發布
[draft] => 12 // 草稿
[pending] => 3 // 待審
[private] => 2 // 私密
[trash] => 7 // 垃圾桶
[auto-draft] => 4 // 自動草稿
[inherit] => 1 // 繼承(附件/修訂版常見)
)
// 方法一:標準寫法(相容 PHP 5.2+) $count_posts = wp_count_posts(); $published = $count_posts->publish; // 方法二:鏈式寫法(需 PHP 5.4+) $published = wp_count_posts()->publish;
$counts = wp_count_posts(); echo '草稿數量:' . $counts->draft; echo '待審數量:' . $counts->pending; echo '垃圾桶數量:' . $counts->trash;
$page_counts = wp_count_posts( 'page' ); echo '已發布頁面:' . $page_counts->publish;
// 假設有名為 'product' 的 CPT $product_counts = wp_count_posts( 'product' ); echo '上架商品:' . $product_counts->publish;
$counts = wp_count_posts( 'post', 'readable' ); // $counts->private 現在包含當前用戶可讀的私密文章
wp_count_posts() 內部使用 wp_cache_get/set(),同一請求中重複呼叫不會產生額外資料庫查詢。若在外掛中大量統計,效能極佳。
WP_Query 與 get_posts()| 方法 | 適用場景 | 效能 | 是否觸發主循環 |
|---|---|---|---|
wp_count_posts() | 僅需統計數字 | ⭐⭐⭐⭐⭐ (有快取) | 否 |
WP_Query + found_posts | 需同時取得文章列表 | ⭐⭐⭐ | 是 |
get_posts() + count() | 簡單列表+計數 | ⭐⭐ (無快取) | 否 |
function site_stats_widget() {
$post_counts = wp_count_posts();
$page_counts = wp_count_posts( 'page' );
$total_published = $post_counts->publish + $page_counts->publish;
$total_drafts = $post_counts->draft + $page_counts->draft;
echo '<div class="site-stats">';
echo '<p>📝 已發布文章:' . number_format_i18n( $post_counts->publish ) . '</p>';
echo '<p>📄 已發布頁面:' . number_format_i18n( $page_counts->publish ) . '</p>';
echo '<p>📊 總發布內容:' . number_format_i18n( $total_published ) . '</p>';
echo '<p>🗂️ 草稿總數:' . number_format_i18n( $total_drafts ) . '</p>';
echo '</div>';
}
// 加入側邊欄或儀表板 Widget 即可
核心檔案:wp-includes/post.php(約第 2800 行起)
wp_count_posts() 統計全站所有符合條件的文章。WP_Query 配合 tax_query 或 get_terms() 取得分類物件的 count 屬性。switch_to_blog() 迴圈遍歷各子站點呼叫本函數並累加。