How to disable comments by default for new pages in WordPress

Whilst developing our first WordPress theme, I came across a small problem regarding the ‘Allow comments’ option for Pages (not Posts or other post types). The requirement for this theme – rightly or wrongly – is to disable comments automatically for new pages, regardless of your setting under the Settings -> Discussion menu.

I thought this would be straightforward, and people in the office assured me that other themes do the same thing. However, like most things, it turned our to be a bit more involved.

Other solutions I found involved disabling comments altogether for Pages (e.g. by not calling the comments template), thus rendering the ‘Allow comments’ checkbox totally useless. Or doing other hacky things like disabling the checkbox so it couldn’t be clicked.

Anyway, after a bit of digging round the core, I found a solution I was reasonably happy with. This approach doesn’t involve editing your page templates so is more future proof and less prone to error — it simply unchecks the ‘Allow comments’ box for all newly created pages so you don’t have to worry about uncheking it yourself as a manual task.

If you need to do something similar, try adding this to your theme:

// Automatically close comments for new pages, regardless of the default comment status option in Settings->Discussion
function close_comments_for_new_pages($post_data, $post_array) {

    // Check this is a newly created page - post ID should be 0 and post status should be 'auto-draft'
    if (isset($post_array['post_type']) && ($post_array['post_type'] === 'page') &&
        isset($post_array['ID']) && ($post_array['ID'] === 0) && 
        isset($post_array['post_status']) && ($post_array['post_status'] === 'auto-draft')) {

        // Close comments
        $post_data['comment_status'] = 'closed';
    }
    return $post_data;
}
add_filter('wp_insert_post_data', 'close_comments_for_new_pages', 10, 2);