Using WordPress ‘comments_open()’ PHP function

The comments_open() WordPress PHP function checks if the current post is open for comments.


Here’s a general usage example of comments_open():

if ( comments_open() ) {
    echo 'Comments are open!';
} else {
    echo 'Comments are closed!';

In this example, if the current post allows comments, it will output ‘Comments are open!’, otherwise it will output ‘Comments are closed!’.


  • $post (int|WP_Post) (Optional) Post ID or WP_Post object. Default is the current post.

More information

See WordPress Developer Resources: comments_open()

This function has been in use since early versions of WordPress and there’s no deprecation information as of now.


Enqueue a script only if comments are open

This code will enqueue a script only if the current post is a single post and comments are open for it.

function enqueue_my_script(){
    if ( is_single() && comments_open() ) {
        wp_enqueue_script( 'my_script' );
add_action( 'wp_print_scripts', 'enqueue_my_script' );

Disable comments on pages

This code will disable comments on all pages. This is useful if your theme uses comments_open() to check if the comments are open.

function disable_page_comments( $open, $post_id ) {
    $post = get_post( $post_id );
    if ( 'page' == $post->post_type ) 
        $open = false;
    return $open;
add_filter( 'comments_open', 'disable_page_comments', 10, 2 );

Completely disable commenting

This code will completely disable commenting on your website.

add_filter( 'comments_open', '__return_false' );

Enable comments based on a custom field

This code will enable comments on a post if it has a custom field “Allow Comments” set to 1. Useful when you want to enable comments for specific old posts.

function enable_comments_based_on_meta( $open, $post_id ) {
    $post = get_post( $post_id );
    if (get_post_meta($post->ID, 'Allow Comments', true)) {
        $open = true;
    return $open;
add_filter( 'comments_open', 'enable_comments_based_on_meta', 10, 2 );

Display a message based on comments status

This code will display a different message based on whether the comments are open or closed for the current post.

if ( comments_open() ) {
    echo 'Feel free to leave a comment!';
} else {
    echo 'Sorry, comments are closed for this post.';