Wednesday, July 18, 2012

KB: JavaScript Files in WordPress Child Themes

An example of how to include custom JavaScript files in WordPress using a child theme.

Contents

Overview

This is a quick example of how to include the copy of jQuery that comes with WordPress as well as a few custom JavaScript files from a child theme. This article assumes the child theme has been created and is working properly.

The solution will use a custom init action and function that will be added to the child theme's functions.php file. The function will call wp_enqueue_script() to load the WordPress jQuery library once. The function will then use get_bloginfo('stylesheet_directory') to get the base URL of the child theme.

The final lines of code will again use the wp_enqueue_script() function to load the JavaScript files that are located within the child theme directory structure.

Example

Here is the resulting action and function that is added to the child theme's functions.php file:
<?php

    // Add child theme javascripts
    add_action('init', 'add_javascript');

    function add_javascript() {
        // Add JQuery
        wp_enqueue_script('jquery');

        // Add the scripts
        $js_url = get_bloginfo('stylesheet_directory') . '/js';
        wp_enqueue_script('tinynav',"$js_url/tinynav.min.js");
        wp_enqueue_script('responsiveslides',"$js_url/responsiveslides.min.js");
    }

?>
For more information, please check the following documentation: To Top