I will try to turn off comments for some posts, belonging to specific categories. This post belongs to a post category named “Uncategorized”, so you should see the comment area is not visible.
This is the code snippet you should add in your function.php in your child theme:
add_filter( 'comments_open', function( $open, $post_id ) {
if ( has_category( array('uncategorized'), $post_id ) ) {
$open = false;
}
return $open;
}, 10, 2 );
You can also use the category ID instead of the category slug. In my case, the post category named “Uncategorized” had ID=1. Here is the code snippet:
add_filter( 'comments_open', function( $open, $post_id ) {
if ( has_category( array(1), $post_id ) ) {
$open = false;
}
return $open;
}, 10, 2 );
Let’s try also with the category name in the code, instead of the category slug or the category ID. So, I will use the next code snippet:
add_filter( 'comments_open', function( $open, $post_id ) {
if ( has_category( array('Uncategorized'), $post_id ) ) {
$open = false;
}
return $open;
}, 10, 2 );
Leave a Reply