Searching WP Comments Before Enqueue

WordPress makes it relatively easy to search through post content before it’s too late to use its wp_enqueue_script or wp_enqueue_style functions. Comments on the other hand don’t have an action hook that is called early enough.

This blog uses Alex Gorbatchev’s Syntax Highlighter for a styled display of code. It’s really easy to implement, but required creating a plugin to check posts and comments for highlighted code. I wanted to load the associated JavaScript and CSS for blog singles and pages when needed, but not load them when there is no code to highlight.

For comments I used the the_posts action hook to check for pre tags in the post contents:

add_action('the_posts', array($this, 'pre_tag_check'));

Because I could not find a suitable action hook for the post comments, I decided to let the comment count in the post data trigger a query for any comments. The query itself checks for the pre tags, but it’s necessary to determine what kind of code will be highlighted, so there is further processing involved. I’m leaving that out in the example code below, because I really want this blog post to focus on the retrieval of comments:

foreach( $posts as $post )
{
  if( $post->comment_count )
  {
    $comments_query = new WP_Comment_Query;

    $comments = $comments_query->query( array(
      'post_id' => $post->ID,
      'status'  => 'approve',
      'search'  => '<pre class="brush'
    ));

    if( $comments )
    {
      // Determine the specific JS and CSS to load ...
    }
  }
}

So, this obviously isn’t the actual code in my plugin, but it shows the basics of how to search any comment’s content for a specific post. I hope this information might save you some time, or if you have a better way of handling this, please leave a comment!