get_comments_number()

関数の概要

get_comments_number()は、WordPressで特定の投稿またはページに対するコメントの数を取得するための関数です。この関数は、コメント数を動的に取得し、表示したい場合に便利です。

パラメータの説明

get_comments_number()関数は1つのオプションパラメータを受け取ります。

  1. $post_id (int, オプション): コメント数を取得する投稿またはページのID。省略された場合は、現在の投稿またはページが対象になります。

使用例

以下は、get_comments_number()関数を使用して投稿のコメント数を取得し表示する例です。

<?php
// 現在の投稿またはページのコメント数を取得する
$comments_number = get_comments_number();

echo '<p>This post has ' . $comments_number . ' comments.</p>';

特定の投稿のコメント数を取得する例

<?php
// 投稿IDが42の投稿のコメント数を取得する
$post_id = 42;
$comments_number = get_comments_number($post_id);

echo '<p>The post with ID 42 has ' . $comments_number . ' comments.</p>';
?>

カスタマイズ

get_comments_number()関数を使用してコメント数を取得した後、コメント数に基づいて異なるメッセージを表示することもできます。

<?php
$comments_number = get_comments_number();

if ($comments_number == 0) {
    echo '<p>No comments yet. Be the first to comment!</p>';
} elseif ($comments_number == 1) {
    echo '<p>There is one comment on this post.</p>';
} else {
    echo '<p>There are ' . $comments_number . ' comments on this post.</p>';
}
?>

関連する関数

  • comments_number(): 現在の投稿またはページのコメント数を表示します。
  • get_comment_count(): 特定の投稿またはページのコメント数の詳細情報を取得します。
  • get_comments(): コメントのリストを取得します。
  • wp_count_comments(): サイト全体のコメント数を取得します。
  • comment_text(): コメントの内容を表示します。