Since threaded comments were enabled in WordPress 2.7, most themes include the following line in header.php

<?php if ( is_singular() ) wp_enqueue_script( 'comment-reply' ); ?>

This code checks if the visitor is browsing either a page or a post and adds the JavaScript required for threaded comments if they are.

I prefer a slight variation

<?php
if ( is_singular() AND comments_open() AND (get_option('thread_comments') == 1))
  wp_enqueue_script( 'comment-reply' );
?>

My variation checks if the visitor is browsing either a page or a post, if comments are open for the entry, and finally, if threaded comments are enabled. If all of these conditions are met, the JavaScript required for threaded comments is added.

If you run your wp_enqueue_script calls in functions.php, as I do, this is the code to use:

<?php
function theme_queue_js(){
  if (!is_admin()){
    if ( is_singular() AND comments_open() AND (get_option('thread_comments') == 1))
      wp_enqueue_script( 'comment-reply' );
  }
}
add_action('wp_print_scripts', 'theme_queue_js');
?>

The call is added to the wp_print_scripts action as is_singular and comments_open are unknown during the init action.

Updated Aug 15 ’09: Fixed two typos in the final code sample

Updated Jun 13 ’10: Changed action in final code block from get_header to wp_print_scripts. Either action works but wp_print_scripts has a closer relationship with the task being performed than the former.

Props to Digging Into WordPress for the …the right way… terminology:)

About Peter Wilson

Peter Wilson is a Web Developer based in Melbourne, Australia. He co-founded Web Production firm Soupgiant with Josh Kinal in October 2009.

2 Comments

  1. Matt Hill says:

    Very handy. I’ve been transferring my base theme from each new version of WP to the next, and didn’t realise I wasn’t including this!

  2. Hi Peter,

    Thanks a lot for your tips. I just started using WordPress for my own site and I’m glad that there is useful information like yours out there.

    Bye, Christine (aks @stinie)

Leave a Reply

Your email is never shared.