Function and usage of get_approved_comments() in wordpress


Answers ( 1 )


    The get_approved_comments() function in WordPress is used for retrieving approved comments related to a specific post. This function is valuable for developers working with WordPress, as it allows them to easily access and display comments that have been approved for a particular post.

    Function Signature:

    get_approved_comments( int $post_id, array $args = array() ): WP_Comment[]|int[]|int


    • Purpose: Retrieves the approved comments for a post.
    • Usage: Primarily used in themes or plugins to fetch comments that are already approved by the administrator or moderator.


    1. $post_id (int, required): The ID of the post for which you want to retrieve the comments.
    2. $args (array, optional): An array of arguments to filter or sort the comments. The function uses WP_Comment_Query::__construct() for handling these arguments. Common arguments include:
      • status (int): Comment status to limit results by. Defaults to approved comments.
      • post_id (int): Limit results to comments affiliated with a given post ID.
      • order (string): Determines how the retrieved comments are ordered. The default value is 'ASC' (ascending).

    Default Argument:

    • The default value for $args is an empty array (array()).

    Return Value:

    • WP_Comment[]|int[]|int: The function returns an array of WP_Comment objects if comments are found. If the $count argument is set to true within $args, it returns the number of approved comments as an integer.

    Sample Usage:

    Here's an example of how get_approved_comments() might be used in a WordPress theme or plugin:

    $post_id = get_the_ID(); // Get the current post ID
    $approved_comments = get_approved_comments($post_id);
    foreach ($approved_comments as $comment) {
        // Display each comment or perform other actions
        echo '<p>' . $comment->comment_content . '</p>';

    In this example, get_the_ID() is used to get the current post's ID, and get_approved_comments() fetches the approved comments for that post. The comments are then looped through, and their content is displayed.


    • This function is part of WordPress's extensive plugin and theme development API, making it easier for developers to interact with comments on a WordPress site.
    • Always consider security and privacy when displaying comments, especially in regard to escaping output to prevent XSS attacks. WordPress provides functions like esc_html() for this purpose.

Leave an answer