WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/comments open

Description

This Conditional Tag checks if comments are allowed for the current Post or a given Post ID. This is a boolean function, meaning it returns either TRUE or FALSE.

Usage

<?php comments_open$post_id ); ?>

Parameters

$post_id
(integer) (optional) The post ID
Default: 0

Return Values

(boolean) 
True on success, false on failure.

Examples

With this code you can always disable comments on pages, assuming your theme uses comments_open() to check if the comments are open.

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;
}

With this code you can enable comments on a post that has custom field "Allow Comments" set to 1. This is helpful when you have told WordPress to disable comments for posts that are older than X days but wish to enable comments for a handful of old posts.

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

function my_comments_open( $open, $post_id ) {

	$post = get_post( $post_id );

        if (get_post_meta($post->ID, 'Allow Comments', true)) {$open = true;}

	return $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', 'myplugin_scripts' );
function myplugin_scripts(){
  if ( is_single() && comments_open() ) {
    // myplugin_script must have been previously registered via wp_register_script()
    wp_enqueue_script( 'myplugin_script' );
  }
}

Notes

Change Log

Since: 1.5.0

Source File

comments_open() is located in wp-includes/comment-template.php.

Related

See also index of Function Reference and index of Template Tags.