comments_open()
Checks if commenting is open for the specified post.
The result returned by this function can be modified through the comments_open filter.
Hooks from the function
Returns
true|false. true if comments can be left on the post and false if they cannot.
Usage
comments_open( $post_id );
- $post_id(int|WP_Post)
- ID of the post for which to check the permission to leave comments. If not specified, the result will return for the current post.
Default: null
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.8.3
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 );
}