Using WordPress ‘get_approved_comments()’ PHP function

The get_approved_comments() WordPress PHP function retrieves the approved comments for a specific post.

Usage

get_approved_comments($post_id, $args);

Custom example:

Input:

$post_id = 1;
$args = array('order' => 'DESC');
get_approved_comments($post_id, $args);

Output:

An array of approved comments for post ID 1, ordered by descending order.

Parameters

  • $post_id (int) – The ID of the post.
  • $args (array) – Optional. See WP_Comment_Query::__construct() for information on accepted arguments.

More information

See WordPress Developer Resources: get_approved_comments()

Examples

Display approved comments for a specific post

This example displays the approved comments for a specific post ID.

$post_id = 1;
$comments = get_approved_comments($post_id);

foreach ($comments as $comment) {
    echo "<strong>" . $comment->comment_author . "</strong>: " . $comment->comment_content . "<br>";
}

Display approved comments with a custom order

This example displays the approved comments for a specific post ID, ordered by ascending order.

$post_id = 1;
$args = array('order' => 'ASC');
$comments = get_approved_comments($post_id, $args);

foreach ($comments as $comment) {
    echo "<strong>" . $comment->comment_author . "</strong>: " . $comment->comment_content . "<br>";
}

Display approved comments with a specific comment type

This example displays the approved comments for a specific post ID, filtering by a specific comment type (in this case, ‘comment’).

$post_id = 1;
$args = array('type' => 'comment');
$comments = get_approved_comments($post_id, $args);

foreach ($comments as $comment) {
    echo "<strong>" . $comment->comment_author . "</strong>: " . $comment->comment_content . "<br>";
}

Display approved comments with a custom number

This example displays a limited number of approved comments for a specific post ID.

$post_id = 1;
$args = array('number' => 5);
$comments = get_approved_comments($post_id, $args);

foreach ($comments as $comment) {
    echo "<strong>" . $comment->comment_author . "</strong>: " . $comment->comment_content . "<br>";
}

Display approved comments with a specific author email

This example displays the approved comments for a specific post ID, filtering by a specific author email.

$post_id = 1;
$args = array('author_email' => '[email protected]');
$comments = get_approved_comments($post_id, $args);

foreach ($comments as $comment) {
    echo "<strong>" . $comment->comment_author . "</strong>: " . $comment->comment_content . "<br>";
}