How to restrict comments counts on WordPress Pages and Posts

Well written articles get appreciations as comments and replies to these comments. But when these comments are good enough if these comments are:

  1. Too Old (posted at 15 March, 2010)
  2. Too Many (over 500)

So better to show latest and fresh comments under article. This situation was faced by one of my client and ask me to write some script to restrict comments on Pages and Posts in WordPress site.

Below is very smart script you can add into your theme’s `functions.php` file

First thing first, you need to set limit for comments on, so just set it here in code:

$comments_allowed = 25;

Then we are adding a filter to hook for comments:

add_filter('the_comments', 'restrict_comments', 1);

 

Finally a callback function to filter the comments and apply our limit we just set above:

function restrict_comments($comments_array){

    if(is_singular()){

        global $comments_allowed;
        if(count($comments_array) > $comments_allowed){

            $remove_index = count($comments_array) - $comments_allowed;
            for($c=0; $c < $remove_index; $c++){

                unset($comments_array[$c]);
            }
        }

    }

    return $comments_array;
}

That’s all, Here is all code just put under `functions.php` file into your active theme:

$comments_allowed = 25;

add_filter('the_comments', 'restrict_comments', 1);

function restrict_comments($comments_array){

    if(is_singular()){

        global $comments_allowed;
        if(count($comments_array) > $comments_allowed){

            $remove_index = count($comments_array) - $comments_allowed;
            for($c=0; $c < $remove_index; $c++){

                unset($comments_array[$c]);
            }
        }

    }

    return $comments_array;
}

If you love it please share this article.

Next: How make plugin to restrict comments rather then pasting this code into Themes file.

Leave a Reply

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

Contact Us

Give us a call or fill in the form below and we will contact you. We endeavor to answer all inquiries within 24 hours on business days.

    Your Name (required)

    Your Email (required)

    Subject

    Your Message