Using WordPress ‘get_comment_meta()’ PHP function

The get_comment_meta() WordPress PHP function retrieves metadata for a specific comment.

Usage

To use the get_comment_meta() function, you would typically provide the comment ID, the metadata key, and a boolean flag indicating whether to return a single value or an array of values.

get_comment_meta($comment_id, $key = '', $single = false);

Parameters

  • $comment_id (int) – Required: The ID of the comment.
  • $key (string) – Optional: The metadata key to retrieve. By default, returns data for all keys (default: ”).
  • $single (bool) – Optional: Whether to return a single value. This parameter has no effect if $key is not specified (default: false).

More information

See WordPress Developer Resources: get_comment_meta

Examples

Retrieve a single metadata value

Retrieve the ‘vote’ metadata for a specific comment.

$comment_id = 42;
$vote = get_comment_meta($comment_id, 'vote', true);

Retrieve all metadata for a comment

Retrieve all metadata associated with a comment.

$comment_id = 42;
$all_meta = get_comment_meta($comment_id);

Retrieve multiple metadata values for a key

Get all values for the ‘rating’ key associated with a specific comment.

$comment_id = 42;
$ratings = get_comment_meta($comment_id, 'rating');

Check if a comment has a specific metadata key

Check if the comment with a specific ID has the ‘review’ key in its metadata.

$comment_id = 42;
$has_review = get_comment_meta($comment_id, 'review', true) != '';

Retrieve metadata from a comment within the comments loop

Get the ‘author_website’ metadata value for a comment within the WordPress comments loop.

while (have_comments()) {
    the_comment();
    $author_website = get_comment_meta(get_comment_ID(), 'author_website', true);
}