Open or Close Comments for the particular post type or post id

WordPress comes with a rich source of features and among them, one is a Comments on a post. Sometimes as an administrator or an author, we don’t like to show the comments section on specific post types or a specific post.

What if that particular post type generated from the plugin?

In that case, as a developer, one need to customize that post type features without editing the plugin and that can be done in WordPress using the filters.

To open or close the comments for specific post type or post, you need to work on ‘comments_open’ filter which has 10 as a priority and two arguments to the callback function.

Two arguments are:

  1. `boolean $open` which indicates Whether the current post is open for comments.
  2. `int $post_id` which indicates Post ID.

WordPress Snippet: How to filter to open or close comments on specific post type or post by post id.

You need to pass post type or post id (as per your requirement) and need to change variable `$open` to false to close the comments and `$open` to true to open the comments.

Before

Open or Close Comments

/**
 * See if comments are open or close and perform a necessary action.
 *
 * @since  3.1.0
 * @param  bool $open    Whether the current post is open for comments.
 * @param  int  $post_id Post ID.
 * @return bool
 */
function geekerhub_comments_open( $open, $post_id ) {
    /*To close comments on specific post type*/
    if ( 'product' === get_post_type( $post_id ) ) {
        $open = false;
    }

    /*To close comments on specific post by post id*/
    if ( 121 ===  $post_id  ) {
        $open = false;
    }

    return $open;
}

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

After

Open or Close Comments

How to use this snippet in your WordPress Site?

This WordPress snippet can be placed at the bottom of the child theme’s functions.php before PHP close tag if exists OR you can place this snippet in your main theme’s functions.php if child theme does not exist. It is mandatory that you know how to edit such files.

Let us know whether snippets still work or not.

I would be happy if there is no issue with the snippet but would be happier if snippet does not work and you let me know. If snippet does not work then I will be enthusiastic to revise the snippets and come with the latest changes. You can let me know about snippet status via the comments section, contact us or via email address ‘iahmed964@gmail.com’

1 thought on “Open or Close Comments for the particular post type or post id”

Leave a Comment

Your email address will not be published. Required fields are marked *