One does not simply throw <link>
(CSS) or <script>
tags into the <head>
of a WordPress theme.
The right way to do it: Register, enqueue … tadaa!
WordPress has the “Dependency API” for this task. It consists basically out of those public functions:
Then there’re aligning functions to deregister scripts or styles, get data from PHP to JS – for example to use them for localization or AJAX calls – and checks/Conditionals to see if a style or script was registered/enqueued.
How to use them
First, you need to make sure that your header.php
file has the appropriate hook:
wp_head();
Then add function to your themes functions.php
file, like explained on WP Make. As you can see, both scripts and files, use the wp_enqueue_scripts
-hook.
add_action( 'wp_enqueue_scripts', 'wpse82474_load_styles' );
add_action( 'wp_enqueue_scripts', 'wpse82474_load_scripts' );
wpse82474_load_styles()
{
wp_enqueue_style( /* etc. */ );
}
wpse82474_load_scripts()
{
wp_enqueue_script( /* etc. */ );
}
The arguments
The main arguments are the following
wp_enqueue_style( $handle, $src, $deps, $ver, $media );
In the real world (to speak: In your theme), you’ll use it like the following. The examples shows a script that has jQuery
loaded as dependency (in other words: loaded before your enqueued file).
wp_enqueue_script(
'my-theme-script'
,get_template_directory_uri().'/js/custom_script.js'
,array( 'jquery' )
);
Getting the path right
From within a childtheme you’d always want to use get_stylesheet_directory_uri()
and from within a parent or “normal” theme, you’d use get_template_directory_uri()
.
Loading from a subfolder of your child theme would use a path like this:
$stylesheet_path = get_stylesheet_directory_uri().'/css/style.css';
Loading WP scripts & styles shipped with core
In case you want to load files that are already shipped with core, then you can simply enqueue them without and further arguments.
wp_enqueue_script( 'jquery' ); // Load jQuery
The same goes for each and every other script (or style) shipped with core, as you can read in Codex.
If you want to know if a script is already registered, there’s no need to look in core or search in Codex. Simply use wp_script_is()
(or it’s equivalent for styles). Per default this checks the enqueue
list, but you can also use registered
or done
as arguments.
wp_script_is( 'jquery', 'registered' ) AND wp_enqueue_script( 'jquery' );