首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

WordPress wp_count_posts 函數詳解:精準統計文章、頁面與自訂文章類型數量

     編輯:PHP 綜合知識

wp_count_posts() 是 WordPress 內建的高效統計函數,能快速獲取各狀態(已發布、草稿、定時、垃圾桶等)的文章數量。支援所有文章類型(Post、Page、自訂 CPT),並提供快取機制,效能遠優於自行撰寫 SQL 查詢。本文將詳細說明參數、回傳結構、常見用法與進階技巧。

函數語法

wp_count_posts( string $type = 'post', string $perm = '' ): stdClass

參數說明

參數類型預設值說明
$typestring'post'文章類型 slug,如 'post'、'page' 或自訂 CPT 名稱
$permstring''設為 'readable' 時,將私密文章納入統計(需用戶有讀取權限)

回傳值結構

函數回傳 stdClass 物件,屬性對應文章狀態:

stdClass Object
(
    [publish] => 123      // 已發布
    [future]  => 5        // 定時發布
    [draft]   => 12       // 草稿
    [pending] => 3        // 待審
    [private] => 2        // 私密
    [trash]   => 7        // 垃圾桶
    [auto-draft] => 4     // 自動草稿
    [inherit] => 1        // 繼承(附件/修訂版常見)
)

常見使用範例

1. 獲取已發布文章總數(最常用)

// 方法一:標準寫法(相容 PHP 5.2+)
$count_posts = wp_count_posts();
$published = $count_posts->publish;

// 方法二:鏈式寫法(需 PHP 5.4+)
$published = wp_count_posts()->publish;

2. 統計特定狀態的文章數

$counts = wp_count_posts();
echo '草稿數量:' . $counts->draft;
echo '待審數量:' . $counts->pending;
echo '垃圾桶數量:' . $counts->trash;

3. 統計頁面數量

$page_counts = wp_count_posts( 'page' );
echo '已發布頁面:' . $page_counts->publish;

4. 統計自訂文章類型(CPT)

// 假設有名為 'product' 的 CPT
$product_counts = wp_count_posts( 'product' );
echo '上架商品:' . $product_counts->publish;

5. 納入私密文章統計(需登入用戶)

$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 行起)

常見問題 FAQ

Q: 為什麼統計數字與後台顯示不一致?
A: 後台列表表格可能套用了額外過濾(如作者權限、日期篩選),而 wp_count_posts() 統計全站所有符合條件的文章。
Q: 能否統計特定分類下的文章數?
A: 本函數不支援分類過濾。需使用 WP_Query 配合 tax_query 或 get_terms() 取得分類物件的 count 屬性。
Q: 多站點網絡中如何統計所有站點文章?
A: 需使用 switch_to_blog() 迴圈遍歷各子站點呼叫本函數並累加。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved