Comment filtering (search)

You create your own comments_template, it can be a duplicate function of the default one, the only changes are the database queries anyway. But you need your own function as WP doesn’t help you with filters here. SO, name it my_comments_template():

  $filter = mysql_real_escape_string($_POST['comment-filter']);
  if(!empty($filter)) $filter = "AND (comment_content LIKE '%%{$filter}%%' OR comment_author LIKE '%%{$filter}%%')";

  if($user_ID)
    $comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE (comment_post_ID = %d) {$filter} AND (comment_approved = '1' OR (user_id = %d AND comment_approved = '0')) ORDER BY comment_date_gmt", $post->ID, $user_ID));
  elseif(empty($comment_author))
    $comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE (comment_post_ID = %d) {$filter} AND (comment_approved = '1') ORDER BY comment_date_gmt", $post->ID));
  else
    $comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE (comment_post_ID = %d) {$filter} AND (comment_approved = '1' OR (comment_author = %s AND comment_author_email = %s AND comment_approved = '0')) ORDER BY comment_date_gmt", $post->ID, wp_specialchars_decode($comment_author, ENT_QUOTES), $comment_author_email));

then add a simple form in the comments template file:

   <form action="<?php echo get_permalink(); ?>" method="post" id="comment-filter">
     <input type="text" name="comment-filter" rel="<?php _e("Search in comments"); ?>" value="<?php echo esc_attr($_POST['comment-filter']); ?>" size="20" />
   </form>

and of course replace all comments_template() function calls with my_comments_template()

I’m implementing this code into a theme I’m working on. My code is a little bigger as I’ve added ajax & query highlighting… If you want to see it all wait for the 1.3 release of my Atom theme.

One thing I didn’t figure out yet is how to keep $_POST[‘comment-filter’] when navigating trough comment pages. For eg. if you search for something inside 5000 comments and you get 1000 comments containing that text and broken up in pages, when you switch the page the comment filter query is lost and you get 2000 comments displayed again…

This function is really useful on Tech related WordPress sites that have hundreds of comments on posts…

Leave a Comment