Last updated on September 13, 2023

Disable Comments

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Disable comments in WordPress.

Comments are a core feature of WordPress that enable visitors to leave feedback on your posts and pages. However, in some cases, you may want to disable comments entirely, for example, if you’re using WordPress as a static site generator or if you’re receiving too much spam. Here’s an example code snippet to disable WordPress comments:

function wpsnippets_disable_comments() {
    // Remove comment support for posts
    remove_post_type_support( 'post', 'comments' );

    // Remove comment support for pages
    remove_post_type_support( 'page', 'comments' );

    // Remove comments from the admin menu
    remove_menu_page( 'edit-comments.php' );

    // Redirect comment-related URLs to the homepage
    add_action( 'template_redirect', 'wpsnippets_disable_comments_redirect' );
}

function wpsnippets_disable_comments_redirect() {
    global $wp_query;
    if ( is_single() || is_page() || is_attachment() ) {
        if ( have_comments() || comments_open() ) {
            wp_redirect( home_url(), 301 );
            exit;
        }
    }
}

add_action( 'admin_init', 'wpsnippets_disable_comments' );

In this code snippet, we define a function wpsnippets_disable_comments() that removes comment support for posts and pages using the remove_post_type_support() function. We also remove the “Comments” menu item from the WordPress admin menu using the remove_menu_page() function.

Finally, we add an action to the template_redirect hook to redirect comment-related URLs to the homepage using the wpsnippets_disable_comments_redirect() function. This function checks if the current page is a post, page, or attachment, and if comments are open or if there are any comments, it redirects the user to the homepage.

We then use the add_action() function to add the wpsnippets_disable_comments() function to the admin_init hook to disable comments across the site.

With this code in place, comments will be disabled across the site, and any comment-related URLs will be redirected to the homepage. You can modify the code to selectively disable comments for specific post types or pages if needed.

Last updated on September 13, 2023. Originally posted on May 12, 2023.

Leave a Reply

Your email address will not be published. Required fields are marked *