How to Turn Off Comments on WordPress Pages

In this tutorial I will share a simple snippet which allows you to disable / turn Off comments on WordPress Pages.

The snippet is quite simple and does two things

1) It first checks if the post is of type ‘page’. The check is done after the post object is completely created.

2) In case the post belongs to disabled category, the code uses comments_open() filter to close the comments on the page.

Here is the snippet.

Simply paste it to your functions.php file and you will be good to go


add_action( 'the_post', 'st_check_for_page' );
    
function st_check_for_page()
   {

     global $post;
    

     $is_it_a_page =  $post->post_type;
 
       if ($is_it_a_page = 'page') 
          {
               add_filter( 'comments_open', 'st_close_comments_on_page', 10, 2 );
        add_action('wp-enqueue-scripts', 'st_deregister_reply_js' );
  
          } else {
  
              return;
                       } 
        
    }

 function st_deregister_reply_js() 
     {
    wp_deregister_script( 'comment-reply' );

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


Here is an Explanation of the logic behind the script.

1) Hook into the_post action:

According to the codex, the_post allows us to modify the post object  after it has been setup. We are hooking a custom function st_check_for_page which checks if the a page is loaded and then run appropriate filters and actions

2) Check the Post Type. 

We will check if the loaded post is of type ‘ page’  using $post->post_type

4) Run appropriate filter:

In case a page is loaded we will close the comments by hooking to the comments_open filter.

We will hook two functions, st_close_comments_on_page and st_deregister_reply_js.  The role of these functions is to mark comments as closed and De-register the comment-reply.js respectively.

Well thats it. This snippet is quite straight forward. Simply paste it in your functions.php file and you are good to go.

Leave a Comment