Edit: Thanks for your replies, guys. This is exactly what I was after. You each brought up some good points. I think I'll stick with using constants.
This is really a best practices/performance question.
I'm mainly concerned with the following functions:
get_template_directory_uri()
get_template_directory()
get_stylesheet_directory_uri()
get_stylesheet_directory()
I've been under the impression that it is bad practice to repeatedly call a function over and over in certain situations. So, this would be considered bad practice:
// Pattern 1
wp_enqueue_script( 'test-1', get_template_directory_uri() . '/js/test-1.js', 'jquery', '20120206', true );
wp_enqueue_script( 'test-2', get_template_directory_uri() . '/js/test-2.js', 'jquery', '20120206', true );
wp_enqueue_script( 'test-3', get_template_directory_uri() . '/js/test-3.js', 'jquery', '20120206', true );
And this would be better:
// Pattern 2
$template_directory_uri = get_template_directory_uri();
wp_enqueue_script( 'test-1', $template_directory_uri . '/js/test-1.js', 'jquery', '20120206', true );
wp_enqueue_script( 'test-2', $template_directory_uri . '/js/test-2.js', 'jquery', '20120206', true );
wp_enqueue_script( 'test-3', $template_directory_uri . '/js/test-3.js', 'jquery', '20120206', true );
I've seen some themes initialize constants:
// Pattern 3
define( 'THEME_URI', get_template_directory_uri() );
define( 'THEME_JS', trailingslashit( BASETHEME_THEME_URI ) . 'js/' );
// Then, later on...
wp_enqueue_script( 'test-1', THEME_JS . 'test-1.js', 'jquery', '20120206', true );
wp_enqueue_script( 'test-2', THEME_JS . 'test-2.js', 'jquery', '20120206', true );
wp_enqueue_script( 'test-3', THEME_JS . 'test-3.js', 'jquery', '20120206', true );
I'm getting the impression that using constants is not such a good idea, even if they are initialized using get_template_directory_uri()
et al., because they can be inflexible. Here's a ticket in WP trac where the constant approach got the boot. Taking a look at _s, (sample below), they are (potentially) calling get_template_directory_uri()
multiple times.
I know this isn't a huge deal, but I run into this question all the time, and see it done differently in themes and plugins. Can you guys help me to set the record straight?
// ...sample code from _s using the multiple calls to get_template_directory_uri()
/**
* Enqueue scripts and styles
*/
function _s_scripts() {
global $post;
wp_enqueue_style( 'style', get_stylesheet_uri() );
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'small-menu', get_template_directory_uri() . '/js/small-menu.js', 'jquery', '20120206', true );
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
if ( is_singular() && wp_attachment_is_image( $post->ID ) ) {
wp_enqueue_script( 'keyboard-image-navigation', get_template_directory_uri() . '/js/keyboard-image-navigation.js', array( 'jquery' ), '20120202' );
}
}
add_action( 'wp_enqueue_scripts', '_s_scripts' );