wp_set_comment_status() │ WP 1.0.0
Sets the comment status: hold, approve, spam.
After setting the status, the hook wp_set_comment_status is triggered.
The status is set in the comment_approved field of the comments table.
Possible values for this field:
0 - hold
1 - approve
spam
trash
Returns
bool|WP_Error. true — the status was successfully set. false — the status could not be set.
Usage
wp_set_comment_status( $comment_id, $comment_status );
- $comment_id(integer) (required)
- ID of the comment.
- $comment_status(string) (required)
The status of the comment to be set. Can be:
- hold / 0
- approve / 1
- spam
- trash
Examples
#1 Allow a comment with ID = 9 that is on approvement
wp_set_comment_status( 9, '1' );
Put it back to the approve status:
wp_set_comment_status( 9, '0' );
#2 How do we get comment status for a post
$get_post = get_post( 123 );
$status = $get_post->comment_status;
// do something only when comments are open
if ( $status === 'open' ) {
// do ...
}Notes
Global. wpdb. $wpdb WordPress database abstraction object. |
Changelog
wp_set_comment_status() wp set comment status code
WP 7.1.5
function wp_set_comment_status( $comment_id, $comment_status, $wp_error = false ) {
global $wpdb;
switch ( $comment_status ) {
case 'hold':
case '0':
$status = '0';
break;
case 'approve':
case '1':
$status = '1';
add_action( 'wp_set_comment_status', 'wp_new_comment_notify_postauthor' );
break;
case 'spam':
$status = 'spam';
break;
case 'trash':
$status = 'trash';
break;
default:
return false;
}
$comment_old = clone get_comment( $comment_id );
if ( ! $wpdb->update( $wpdb->comments, array( 'comment_approved' => $status ), array( 'comment_ID' => $comment_old->comment_ID ) ) ) {
if ( $wp_error ) {
return new WP_Error( 'db_update_error', __( 'Could not update comment status.' ), $wpdb->last_error );
} else {
return false;
}
}
clean_comment_cache( $comment_old->comment_ID );
$comment = get_comment( $comment_old->comment_ID );
/**
* Fires immediately after transitioning a comment's status from one to another in the database
* and removing the comment from the object cache, but prior to all status transition hooks.
*
* @since 1.5.0
*
* @param string $comment_id Comment ID as a numeric string.
* @param string $comment_status Current comment status. Possible values include
* 'hold', '0', 'approve', '1', 'spam', and 'trash'.
*/
do_action( 'wp_set_comment_status', $comment->comment_ID, $comment_status );
wp_transition_comment_status( $comment_status, $comment_old->comment_approved, $comment );
wp_update_comment_count( $comment->comment_post_ID );
return true;
}
Related Functions