get_comments() の使い方|説明・引数・注意点

説明

get_comments() は、条件を指定してコメントを取得する関数です。

基本構文

get_comments( array|string $args = '' ): WP_Comment[]|int[]|int

引数

  • $args:post_id、status、number、orderby など

戻り値

コメントの配列。

使い方(サンプル)

$comments = get_comments( array( 'post_id' => 123, 'status' => 'approve' ) );

注意点

  • 承認済みだけを取得するなら status => 'approve' を指定します。

実務での使いどころ

  • 投稿のコメントの、一覧を取得するとき。
  • 最新のコメントを、サイドバーなどに、表示するとき。
  • コメントの件数を、取得するとき('count' => true)。

よくあるミスと対処

  • status を、指定していない。承認待ちのコメントも、含まれる。公開するコメントだけなら、'status' => 'approve' を指定する。
  • number を、指定していない。件数が多いと、大量のコメントを、取得する。
  • コメントの本文などを、エスケープせずに、出力している。

NG例

$comments = get_comments( array( 'post_id' => $id ) ); // 承認待ちも含まれる

OK例

$comments = get_comments( array(
	'post_id' => $id,
	'status'  => 'approve',
	'number'  => 10,
) );
foreach ( $comments as $c ) {
	echo esc_html( $c->comment_content );
}

使い分け早見表

関数 役割
get_comments() コメントの一覧を、取得する
wp_insert_comment() コメントを、直接追加する
comments_template() コメント欄を、読み込む

関連項目

wp_insert_comment()、get_comments_number()

公式リファレンス:get_comments() | Function | WordPress Developer Resources

コメント

タイトルとURLをコピーしました