wp_count_comments
Allows you to change the comment count for a specified post or for the site as a whole.
Usage
add_filter( 'wp_count_comments', 'wp_kama_count_comments_filter', 10, 2 );
/**
* Function for `wp_count_comments` filter-hook.
*
* @param array|stdClass $count An empty array or an object containing comment counts.
* @param int $post_id The post ID. Can be 0 to represent the whole site.
*
* @return array|stdClass
*/
function wp_kama_count_comments_filter( $count, $post_id ){
// filter...
return $count;
}
- $count(array)
- An empty array.
- $post_id(integer)
- The post ID.
Examples
#1 Disable the comment count query
Suppose the site does not use comments. It makes sense to remove references to them from the admin area.
add_action( 'admin_menu', 'remove_admin_menu_comments' );
add_action( 'add_admin_bar_menus', 'remove_admin_bar_comments' );
add_action( 'wp_dashboard_setup', 'remove_dashboard_recent_comments' );
/**
* Remove the “Comments” menu item from the admin area.
*
* @return void
*/
function remove_admin_menu_comments() {
remove_menu_page( 'edit-comments.php' );
}
/**
* Remove the “Comments” menu item from the toolbar.
*
* @return void
*/
function remove_admin_bar_comments() {
remove_action( 'admin_bar_menu', 'wp_admin_bar_comments_menu', 60 );
}
/**
* Remove the “Recent Comments” widget from the WordPress Dashboard.
*
* @return void
*/
function remove_dashboard_recent_comments() {
$dash_side = &$GLOBALS['wp_meta_boxes']['dashboard']['side']['core'];
$dash_normal = &$GLOBALS['wp_meta_boxes']['dashboard']['normal']['core'];
unset( $dash_normal['dashboard_recent_comments'] );
}
Despite these removals, the site comment count query still runs in menu.php, where it is no longer useful. Disable this and similar comment count queries for both a specified post and the site as a whole:
add_filter( 'wp_count_comments', 'wp_count_comments_empty' );
function wp_count_comments_empty() {
return (object) [
'approved' => 0,
'awaiting_moderation' => 0,
'moderated' => 0,
'spam' => 0,
'trash' => 0,
'post-trashed' => 0,
'total_comments' => 0,
'all' => 0,
];
}Changelog
| Since 2.7.0 | Introduced. |
Where the hook is called
wp_count_comments
wp-includes/comment.php 1529
$filtered = apply_filters( 'wp_count_comments', array(), $post_id );