wp_update_comment_count()
Updates the comment count for post(s).
When $do_deferred is false (is by default) and the comments have been set to be deferred, the post_id will be added to a queue, which will be updated at a later date and only updated once per post ID.
If the comments have not be set up to be deferred, then the post will be updated. When $do_deferred is set to true, then all previous deferred post IDs will be updated along with the current $post_id.
No Hooks.
Return
true|false|null
. True on success, false on failure or if post with ID does not exist.
Usage
wp_update_comment_count( $post_id, $do_deferred );
- $post_id(int|null) (required)
- Post ID.
- $do_deferred(true|false)
- Whether to process previously deferred post comment counts.
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. |