The comments_open WordPress PHP filter checks if the current post is open for comments.
Usage
apply_filters('comments_open', $open, $post_id);
Parameters
$open
(bool) – Whether the current post is open for comments.$post_id
(int) – The post ID.
More information
See WordPress Developer Resources: comments_open
Examples
Disable comments on a specific post
add_filter('comments_open', 'disable_comments_on_specific_post', 10, 2); function disable_comments_on_specific_post($open, $post_id) { if ($post_id == 123) { // Replace 123 with the post ID you want to disable comments for return false; } return $open; }
Close comments on older posts
add_filter('comments_open', 'close_comments_on_older_posts', 10, 2); function close_comments_on_older_posts($open, $post_id) { $post_date = get_post($post_id)->post_date; $days_old = (time() - strtotime($post_date)) / 86400; // Calculate days since post date if ($days_old > 30) { // Close comments on posts older than 30 days return false; } return $open; }
Open comments for logged-in users only
add_filter('comments_open', 'comments_for_logged_in_users_only', 10, 2); function comments_for_logged_in_users_only($open, $post_id) { if (!is_user_logged_in()) { return false; } return $open; }
Disable comments on posts with specific tags
add_filter('comments_open', 'disable_comments_on_specific_tags', 10, 2); function disable_comments_on_specific_tags($open, $post_id) { $tags_to_disable = array('no-comments', 'private'); // List of tags to disable comments for $post_tags = wp_get_post_tags($post_id, array('fields' => 'slugs')); // Get the slugs of post tags if (array_intersect($tags_to_disable, $post_tags)) { return false; } return $open; }
Enable comments on specific post types
add_filter('comments_open', 'enable_comments_on_specific_post_types', 10, 2); function enable_comments_on_specific_post_types($open, $post_id) { $post_type = get_post_type($post_id); $allowed_post_types = array('custom_type_1', 'custom_type_2'); // List of post types to allow comments if (in_array($post_type, $allowed_post_types)) { return true; } return $open; }