This code snippet provides a way to completely disable comments on a WordPress website. This may be useful for sites where user interaction is not a requirement or where comments have become a target for spam.
The provided script does several things:
- It redirects users trying to access the comments page in the WordPress admin area back to the main dashboard.
- It removes the recent comments metabox from the dashboard.
- It loops through all registered post types and removes support for comments and trackbacks.
- It filters the
comments_open
andpings_open
checks to always return false, effectively closing comments on the front end of the site. - It filters the
comments_array
to always return an empty array, hiding existing comments. - It removes the comments menu page from the WordPress admin area.
- It removes the comments link from the admin bar.
Add this code to your theme’s functions.php file to disable comments on your WordPress site. Note that this should be tested on a staging or local version of your site before implementing it on a live website.
PHP
add_action('admin_init', function () {
// Redirect any user trying to access comments page
global $pagenow;
if ($pagenow === 'edit-comments.php') {
wp_safe_redirect(admin_url());
exit;
}
// Remove comments metabox from dashboard
remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');
// Disable support for comments and trackbacks in post types
foreach (get_post_types() as $post_type) {
if (post_type_supports($post_type, 'comments')) {
remove_post_type_support($post_type, 'comments');
remove_post_type_support($post_type, 'trackbacks');
}
}
});
// Close comments on the front-end
add_filter('comments_open', '__return_false', 20, 2);
add_filter('pings_open', '__return_false', 20, 2);
// Hide existing comments
add_filter('comments_array', '__return_empty_array', 10, 2);
// Remove comments page in menu
add_action('admin_menu', function () {
remove_menu_page('edit-comments.php');
});
// Remove comments links from admin bar
add_action('admin_bar_menu', function () {
remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
}, 0);