Adding Your Own Scripts

When you need to add a JavaScript file to your theme, it's tempting to simply paste the <script> tag into header.php, dust off your hands, and move on to your next task. However, this is the wrong way to add scripts to a WordPress theme. You might recall from Chapter 3 that you can specify the location of the wp-content directory. If someone who has moved wp-content() tries to use this theme, the scripts will never load.

Adding the <script> tags via the wp_head() action, as shown in Listing 7-22, is also not a good idea.

Listing 7-22. How not to link scripts function slider_scripts() { ?>

<script type="text/javascript" src="<?php bloginfo('url'); ?>/wp-content/themes/test-theme/jquery.js"></script>

<script type="text/javascript" src="<?php bloginfo('url'); ?>/wp-content/themes/test-theme/jquery-slider.js"></script> <?php }

add_action('wp_head', 'slider_scripts');

This will get the job done, but it's inefficient. You might have a plugin that has already called the jQuery library; now it will be included twice. It's also a bad idea to hard-code the path to the theme directory.

The correct way to add scripts is to use the wp_enqueue_scripts() function. This function adds your script to the header using the wp_head() hook. Listing 7-23 shows how to enqueue a script in the header using a small function and an action hook in functions.php.

Listing 7-23. Enqueueing scripts function add_header_scripts() {

wp_enqueue_script('header-script', <?php bloginfo('stylesheet_directory');

?>'/js/header-script.js', array('jquery'), '1.0', false); }

add_action('wp_head', 'add_header_scripts');

The wp_enqueue_scripts() function requires several arguments. First, you need to give your script a unique handle, or name. This allows you to refer to it later and ensures that only one script of that name will be included in the page. Next, you need to provide the URL to your script file. Third, if your script relies on any libraries (like jQuery), you need to provide the handles of those dependencies in an array. Fourth, if you need to call a specific version, provide its number. (To use the most recent version, use an empty string for this argument.) Finally, you need to tell WordPress whether the script should be loaded in the footer via wp_footer(). In this case, you want to load the script in the header, so this argument should be false (or blank).

7 Days to Profitable Blogging

7 Days to Profitable Blogging

Learn The Simple Blueprint To Successfully Starting a Profitable Blog In Just 7 Days? MOST blogs fail because their owners start out badly, and continue to make mistakes. By the time they realize what's gone wrong, they would be quicker restarting!

Get My Free Ebook

Post a comment