comments_open()
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.
Hooks from the function
Return
true|false
. True if the comments are open.
Usage
comments_open( $post );
- $post(int|WP_Post)
- Post ID or WP_Post object.
Default: current post
Examples
#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(); }
#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.
#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(); }
#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. |
comments_open() comments open code WP 6.7.1
function comments_open( $post = null ) { $_post = get_post( $post ); $post_id = $_post ? $_post->ID : 0; $comments_open = ( $_post && ( 'open' === $_post->comment_status ) ); /** * Filters whether the current post is open for comments. * * @since 2.5.0 * * @param bool $comments_open Whether the current post is open for comments. * @param int $post_id The post ID. */ return apply_filters( 'comments_open', $comments_open, $post_id ); }