A guide to WordPress wp_set_comment_status function

The wp_set_comment_status function in WordPress is used to change the status of a comment, such as marking it as approved, pending, spam, or trash.

This function can be useful for site administrators who need to manage and moderate comments on their WordPress site. It allows them to easily change the status of individual comments, helping to keep the comment section organized and free of spam.

Parameters Accepted by wp_set_comment_status Function

The wp_set_comment_status function accepts the following parameters:

  • $comment_id (int|WP_Comment) – required. This parameter represents the Comment ID or WP_Comment object.
  • $comment_status (string) – required. This parameter indicates the new comment status, which can be either ‘hold’, ‘approve’, ‘spam’, or ‘trash’.
  • $wp_error (bool) – optional. Default value: false. This parameter determines whether to return a WP_Error object if there is a failure.

Value Returned by wp_set_comment_status Function

The wp_set_comment_status function returns either a boolean value or a WP_Error object. It returns true on success, and false or a WP_Error object on failure.

Examples

How to approve a comment using wp_set_comment_status

<?php
$comment_id = 123;
$status = 'approve';

wp_set_comment_status( $comment_id, $status );
?>

This code snippet uses the wp_set_comment_status function to approve a comment with the ID of 123.

How to mark a comment as spam using wp_set_comment_status

<?php
$comment_id = 456;
$status = 'spam';

wp_set_comment_status( $comment_id, $status );
?>

This code snippet uses the wp_set_comment_status function to mark a comment with the ID of 456 as spam.

How to unapprove a comment using wp_set_comment_status

<?php
$comment_id = 789;
$status = 'hold';

wp_set_comment_status( $comment_id, $status );
?>

This code snippet uses the wp_set_comment_status function to unapprove a comment with the ID of 789, putting it on hold for moderation.

Conclusion

In conclusion, the wp_set_comment_status function provides an effective feature for managing the status of comments on WordPress websites. By allowing developers to easily change the status of comments, this function enables greater control over the moderation and display of user-generated content. Whether it’s marking comments as spam, unapproving inappropriate content, or restoring previously deleted comments, wp_set_comment_status streamlines the process and enhances the overall user experience. With its flexibility and efficiency, this function is a valuable asset for any WordPress developer looking to maintain a high standard of comment management.