‘pre_wp_update_comment_count_now’ is a WordPress PHP filter that allows you to modify a post’s comment count before it gets updated in the database.
Usage
To use this filter, add a custom function to your theme’s functions.php file or a custom plugin, and hook it to the ‘pre_wp_update_comment_count_now’ filter.
add_filter( 'pre_wp_update_comment_count_now', 'your_function_name', 10, 3 );
Parameters
- $new (int|null): The new comment count. Default null.
- $old (int): The old comment count.
- $post_id (int): Post ID.
Examples
Double Comment Count
function double_comment_count( $new, $old, $post_id ) {
return $old * 2;
}
add_filter( 'pre_wp_update_comment_count_now', 'double_comment_count', 10, 3 );
This example doubles the current comment count before updating it in the database.
Minimum Comment Count
function set_minimum_comment_count( $new, $old, $post_id ) {
return max( $old, 10 );
}
add_filter( 'pre_wp_update_comment_count_now', 'set_minimum_comment_count', 10, 3 );
This example sets a minimum comment count of 10, preventing the count from dropping below this value.
Add 5 Comments to Specific Post
function add_five_comments_to_post( $new, $old, $post_id ) {
if ( $post_id == 123 ) {
return $old + 5;
}
return $old;
}
add_filter( 'pre_wp_update_comment_count_now', 'add_five_comments_to_post', 10, 3 );
This example adds 5 comments to the comment count of a specific post with the ID 123.
Exclude Comments from Count by Author
function exclude_author_comments( $new, $old, $post_id ) {
$author_id = 42;
$comments = get_comments( array( 'post_id' => $post_id, 'author__not_in' => array( $author_id ) ) );
return count( $comments );
}
add_filter( 'pre_wp_update_comment_count_now', 'exclude_author_comments', 10, 3 );
This example excludes comments made by an author with the ID 42 from the comment count.
Only Count Approved Comments
function count_only_approved_comments( $new, $old, $post_id ) {
$approved_comments = get_comments( array( 'post_id' => $post_id, 'status' => 'approve' ) );
return count( $approved_comments );
}
add_filter( 'pre_wp_update_comment_count_now', 'count_only_approved_comments', 10, 3 );
This example ensures that only approved comments are counted for the comment count of a post.