wp_update_comment_count()
Updates the number of comments for the specified post.
No Hooks.
Returns
true|false|null. true if the comment count was successfully updated. false otherwise.
Usage
wp_update_comment_count( $post_id, $do_deferred );
- $post_id(integer) (required)
- ID of the post.
- $do_deferred(boolean)
This is an internal parameter that should be managed through the function wp_defer_comment_counting(). It is needed to speed up the import of a large number of comments.
Indicates whether to trigger updates to the comment count of the post that were previously deferred.
No updates occur if the comment is under moderation.
If the parameter
$do_deferredis set to false (default) and the comment is under moderation, the post ID ($post_id) will be added to the queue for future updates. See wp_defer_comment_counting().Default: false
Examples
#1 Usage example
Suppose we deleted comments from the database for post 3. We did it with a direct query to the database.
Now you need to update (int) - the number of comments posts:
$post_id = 3; wp_update_comment_count( $post_id );
#2 Update the post comment count
For example, we have our own non-standard function for adding a comment to the database. Our function use the direct DB query for adding comment to DB. So, we need to use this function to update post comments count, after adding new comment like it dose in wp_new_comment().
/**
* Update or insert a comment.
*
* @access public
*
* @param \WP_Comment $comment Comment object.
*/
function upsert_comment( $comment ) {
global $wpdb;
$comment = $comment->to_array();
// Filter by fields on comment table.
$comment_fields_whitelist = array(
'comment_ID',
'comment_post_ID',
'comment_author',
'comment_author_email',
'comment_author_url',
'comment_author_IP',
'comment_date',
'comment_date_gmt',
'comment_content',
'comment_karma',
'comment_approved',
'comment_agent',
'comment_type',
'comment_parent',
'user_id',
);
foreach ( $comment as $key => $value ) {
if ( ! in_array( $key, $comment_fields_whitelist, true ) ) {
unset( $comment[ $key ] );
}
}
$exists = $wpdb->get_var(
$wpdb->prepare(
"SELECT EXISTS( SELECT 1 FROM $wpdb->comments WHERE comment_ID = %d )",
$comment['comment_ID']
)
);
if ( $exists ) {
$wpdb->update( $wpdb->comments, $comment, array( 'comment_ID' => $comment['comment_ID'] ) );
}
else {
$wpdb->insert( $wpdb->comments, $comment );
}
// Remove comment from cache.
clean_comment_cache( $comment['comment_ID'] );
// Update the data on the number of comments on the post
wp_update_comment_count( $comment['comment_post_ID'] );
}
Notes
- See: wp_update_comment_count_now() For what could cause a false return value
Changelog
| Since 2.1.0 | Introduced. |