Disable WordPress Comments Programmatically

This post exists primarily for my own future reference. Sometimes I want to disable all comments without using a plugin. The code below borrows heavily (maybe even copies blatantly!) from a couple GitHub repositories I came across a while ago:

– https://gist.github.com/mattclements/eab5ef656b2f946c4bfb

– https://gist.github.com/alexwoollam/2f4bcd4eb4740eb49562131290248f26

Here’s the code:

/**
 * Disable post type support for comments
 * 
 * Loops through post types and disables commends for any post types that
 * previously had them enabled.
 */
function prefix_disable_comments_post_types_support() {
    $post_types = get_post_types();
    foreach ( $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' );
        }
    }
}
add_action( 'admin_init', 'prefix_disable_comments_post_types_support' );

/**
 * Disable frontend commenting functionality
 */
function prefix_disable_comments_status() {
    return false;
}
add_filter( 'comments_open', 'prefix_disable_comments_status', 20, 2 );
add_filter( 'pings_open', 'prefix_disable_comments_status', 20, 2 );


/**
 * Disable frontend comment display
 * 
 * Empties the comments array used to populate comments area.
 *
 * @param array $comments Array of existing comments.
 */
function prefix_disable_comments_hide_existing_comments( $comments ) {
    $comments = array();
    return $comments;
}
add_filter( 'comments_array', 'prefix_disable_comments_hide_existing_comments', 10, 2 );

/**
 * Remove comments page in menu.
 */
function prefix_disable_comments_admin_menu() {
    remove_menu_page( 'edit-comments.php' );
}
add_action( 'admin_menu', 'prefix_disable_comments_admin_menu' );

/**
 * Redirect any user trying to access comments page
 */
function prefix_disable_comments_admin_menu_redirect() {
    global $pagenow;
    if ( 'edit-comments.php' === $pagenow ) {
        wp_redirect( admin_url() );
        exit;
    }
}
add_action( 'admin_init', 'prefix_disable_comments_admin_menu_redirect' );

/**
 * Remove comments metabox from dashboard
 */
function prefix_disable_comments_dashboard() {
    remove_meta_box( 'dashboard_recent_comments', 'dashboard', 'normal' );
}
add_action( 'admin_init', 'prefix_disable_comments_dashboard' );

/**
 * Remove comments links from admin bar
 */
function prefix_disable_comments_admin_bar() {
    if ( is_admin_bar_showing() ) {
        remove_action( 'admin_bar_menu', 'wp_admin_bar_comments_menu', 60 );
    }
}
add_action( 'init', 'prefix_disable_comments_admin_bar' );
Posted in

Leave a Comment

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