Table of Contents
ToggleWell written articles get appreciations as comments and replies to these comments. But when these comments are good enough if these comments are:
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.