comments_open()WP 1.5.0

Whether the current post is open for comments.

For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.

Uses: get_post()
1 time — 0.002038 sec (very slow) | 50000 times — 0.81 sec (very fast) | PHP 7.1.5, WP 4.8.1
Hooks from the function

Return

true|false. True if the comments are open.

Usage

comments_open( $post_id );
$post_id(int|WP_Post)
Post ID or WP_Post object.
Default: current post

Examples

0

#1 Check the ability to leave comments on the post

and if it is allowed to leave comments, we will display a comment template.

if( comments_open( $post->ID ) ){
	comments_template();
}
0

#2 Using the comments_open filter

This example shows how to close comments on all static pages ('page' post_type):

add_filter( 'comments_open', 'my_comments_open', 10, 2 );

function my_comments_open( $open, $post_id ) {

	$post = get_post( $post_id );

	if ( 'page' == $post->post_type )
		$open = false;

	return $open;
}

If the comment template is output via validation, as in the first example, then comments_open($post->ID) will return false for all static pages, so the comment template (comments_template()) will not be output.

0

#3 Another test of the ability to leave a comment

Alternatively, you can check the ability to leave comments on the current post as follows:

global $post;

if( 'open' === $post->comment_status ){
	comments_template();
}
0

#4 Add script only if comments are open

Enqueuing a script only if we’re seeing a single post and comments are open for the current post

add_action( 'wp_print_scripts', 'wpdocs_scripts' );

/**
 * Enqueue wpdocs_script if viewing a post with comments enabled.
 */
function wpdocs_scripts(){

	if ( is_single() && comments_open() ) {

		// wpdocs_script must have been previously registered via wp_register_script()
		wp_enqueue_script( 'wpdocs_script' );
	}
}

Changelog

Since 1.5.0 Introduced.

Code of comments_open() WP 6.0.1

function comments_open( $post_id = null ) {

	$_post = get_post( $post_id );

	$post_id = $_post ? $_post->ID : 0;
	$open    = ( $_post && ( 'open' === $_post->comment_status ) );

	/**
	 * Filters whether the current post is open for comments.
	 *
	 * @since 2.5.0
	 *
	 * @param bool $open    Whether the current post is open for comments.
	 * @param int  $post_id The post ID.
	 */
	return apply_filters( 'comments_open', $open, $post_id );
}