Display comments section only for certain categories in WordPress

You may wonder whether it’s possible, yes it’s certainly possible.All you have to do is add the below custom code in functions.php of your theme file or in my-custom-functions plugin

Here is code

add_action( 'the_post', 'Comments_ClosedCategories' );     	
function Comments_ClosedCategories()    
{        
     global $post;       
     $my_post_cat = wp_get_post_categories($post->ID);  
     //Array of Category ID's where you want to disable comments                  
     $disabled_cat = array( "8", "9","10","11","12","20","21","22"); 
     // this is he array of disabled categories..        
     $my_result = array_intersect($my_post_cat,$disabled_cat);       
     if (empty ( $my_result ) )        
     {            return;        
       
     }        
    else        
    {              
        add_filter( 'comments_open', 'st_close_comments_on_category', 10, 2 );             
        add_action('wp_enqueue_scripts', 'st_deregister_reply_js');       
    }   
}       
function st_deregister_reply_js()        
{        
    wp_deregister_script( 'comment-reply' );    
}                                                      

function st_close_comments_on_category ($open, $post_id)         
{              
    $open = false;                       
}       
                
  
        

The above code will leave the comment closed on the categories included in the array and for other categories comment section would be still opened where they can post comments


Scroll to Top