Using WordPress ‘comment_exists()’ PHP function

The comment_exists() WordPress PHP function is used to determine if a comment exists based on the author and date of the comment.

Usage

Here’s a basic example of how to use this function:

$author = 'John Doe';
$date = '2023-04-01 12:30:00';
$timezone = 'gmt';
$comment_exists = comment_exists($author, $date, $timezone);

if ($comment_exists) {
    echo 'The comment exists.';
} else {
    echo 'The comment does not exist.';
}

In this example, we’re trying to find out if a comment by ‘John Doe’ made on ‘2023-04-01 12:30:00’ in GMT timezone exists. The function will return the comment’s ID if it exists or null otherwise.

Parameters

  • $comment_author (string): This is the author of the comment. This parameter is required.
  • $comment_date (string): This is the date of the comment. This parameter is required.
  • $timezone (string): This is the timezone. It accepts either ‘blog’ or ‘gmt’. The default is ‘blog’.

More information

See WordPress Developer Resources: comment_exists()

Examples

Finding a comment from a specific author and date

$author = 'Jane Doe';
$date = '2023-01-15 08:00:00';
$comment_exists = comment_exists($author, $date);

// Output: Comment ID if exists, null otherwise

Here we’re checking if a comment from ‘Jane Doe’ on ‘2023-01-15 08:00:00’ exists. The timezone is defaulted to ‘blog’.

Using GMT timezone

$author = 'John Smith';
$date = '2023-02-01 10:00:00';
$timezone = 'gmt';
$comment_exists = comment_exists($author, $date, $timezone);

// Output: Comment ID if exists, null otherwise

In this case, we’re using the GMT timezone to find a comment from ‘John Smith’ on ‘2023-02-01 10:00:00’.

Comment does not exist

$author = 'Non Existent User';
$date = '2022-12-31 23:59:59';
$comment_exists = comment_exists($author, $date);

// Output: null

This time, we’re looking for a comment from a non-existent user, so the function will return null.

Default timezone (‘blog’)

$author = 'Emily';
$date = '2023-03-01 12:00:00';
$comment_exists = comment_exists($author, $date);

// Output: Comment ID if exists, null otherwise

In this example, the timezone is defaulted to ‘blog’. We’re trying to find a comment from ‘Emily’ on ‘2023-03-01 12:00:00’.

Specify timezone as ‘blog’

$author = 'Alex';
$date = '2023-04-01 16:00:00';
$timezone = 'blog';
$comment_exists = comment_exists($author, $date, $timezone);

// Output: Comment ID if exists, null otherwise

Finally, we’re explicitly setting the timezone to ‘blog’ to find a comment.