萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> CMS 教學

WordPress 獲取全站/單篇文章評論總數的代碼方法

獲取全站已審核評論總數

<?php
global $wpdb;
$numcomms = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1'");
if ( $numcomms > 0 ) {
    $numcomms = number_format_i18n( $numcomms ); // 本地化數字格式(如加千分位)
}
?>

在模板中輸出:

<?php echo '全站共有 ' . $numcomms . ' 條已審核評論'; ?>

獲取單篇文章評論數(含巢狀回覆)

WordPress 內置函數 get_comments_number() 已包含所有類型評論:

<?php
// 在循環中或傳入 $post_id
$count = get_comments_number( $post_id ); 
echo '本文共有 ' . $count . ' 條評論';
?>

或使用 comments_number() 直接輸出本地化字符串:

<?php comments_number( '暫無評論', '1 條評論', '% 條評論' ); ?>

僅統計頂級評論(不含回覆)

<?php
$top_level_count = get_comments( array(
    'post_id' => $post_id,
    'parent'  => 0,        // 只查父評論
    'status'  => 'approve',
    'count'   => true      // 直接返回數量
) );
echo '主評論數:' . $top_level_count;
?>

性能優化建議

  • 全站評論數緩存:使用 Transient API 緩存 1 小時,避免每頁查詢 COUNT(*)。
  • 單篇文章評論數已由 WordPress 緩存(comment_count post meta),直接調用 get_comments_number() 極快。
  • 避免在循環中重複查詢,預先獲取存入變量。
copyright © 萬盛學電腦網 all rights reserved