As you probably know the best way to load scripts in WordPress is to use the wp_enqueue_script function. However the process for loading scripts is slightly different depending on where you’re calling the script from.
There are basically three possibilities:
From Inside a Parent Theme
[php]
wp_enqueue_script( ‘my-awesome-script’, get_template_directory_uri() . ‘/js/my-awesome-script.js’, array(‘jquery’), ‘1.0’ );
[/php]
In this case we use the get_template_directory_uri function
From Inside a Child Theme
[php]
wp_enqueue_script( ‘my-awesome-script’, get_stylesheet_directory_uri() . ‘/js/my-awesome-script.js’, array(‘jquery’), ‘1.0’ );
[/php]
From child themes, on the other hand, we need to use the get_stylesheet_directory_uri function which retrieves theΒ stylesheetΒ directory URI for the current theme/child theme.
From Inside a Plugin
[php]
wp_enqueue_script( ‘my-awesome-script’, plugins_url( ‘/js/my-awesome-script.js’, __FILE__ ), array(‘jquery’), ‘1.0’ );
[/php]
TheΒ plugins_urlΒ template tag retrieves the url to the plugins directory or to a specific file within that directory. You can hardcode the plugin slug in $path or pass __FILE__ as a second argument to get the correct folder name.
Code from Will Anderson’s speech on WordCamp.tv.
If you enjoyed this post, make sure to subscribe to WP Mayor’s RSS feed.
2 Responses
Typo in snippet #3, missing single quote around ‘jquery’. Also, the fourth argument (the version) is expecting a string, but you’re giving it a float. It will work, but the 1.0 float converted to a string results in “1” and not “1.0” so you *might* eventually run into trouble:
var_dump( version_compare( 1.0, ‘1.0’ ) ); // int(-1)
I can’t think of an example right now, but I recommend to always use strings as version numbers. It has other advantages as well, such as “3.5-beta2” π
K
Very valuable input as usual, thanks for pointing it out, code fixed.