Loading jQuery Plugins into Theme Files

Posted on 21st June, 2013 Leave a Comment

My preferred method of adding JavaScript into any theme, is to include a single js sheet called ‘scripts.js‘ then call it in your functions.php.

The only real trick here is to load the script inside a function that declares the dollar sign.

For this example I’m going to add colorbox to the theme but you can follow and adjust this to suit your personal needs.

Folder Structure

So to begin lets create a couple of new folders, just to keep everything tidy.

  •   js
  •   plugins *put this folder inside the first folder.’  js/plugins ‘

inside the plugins folder add the plugin Script files, I say script files because there might be CSS and JavaScript to include. For colorbox to work correctly we’ll need to add the JS, CSS and the images folder that contains the shadows and loading.gif for the colorbox. Also create a blank file called scripts.js and add this to the js folder.

With these added, our folder containing our plugin should now look like this:

js / plugins / Images
scripts.js colorbox.min.js loading.gif
colorbox.css border.png

functions.php

Now include the new plugin to your theme, move the JS folder to your theme file and open up your functions.php.

/**
 * Enqueue scripts and styles
 * Author: WPtricks.co.uk
 */
function new_scripts() {

  //Include our custom js
    wp_register_script( 'new-js', get_stylesheet_directory_uri() . '/js/scripts.js', array( 'jquery' ), '', true );
    wp_enqueue_script( 'new-js' );

  //include Colorbox
    wp_register_script('jquery_colorbox', get_template_directory_uri(). '/js/plugins/jquery.colorbox.min.js', array('jquery'), '' );
    wp_enqueue_style('jquery_colorbox', get_template_directory_uri().'/js/plugins/colorbox.css');
    wp_enqueue_script('jquery_colorbox');
}
add_action( 'wp_enqueue_scripts', 'new_scripts' );

Scripts.js

Then I want to call colorbox on all linked images, add this to your scripts.js file.

/*
Scripts File
Author: WPtricks.co.uk
*/

jQuery(document).ready(function($) {

// Open all images into Colorbox
$('a[href$=".jpg"],a[href$=".jpeg"],a[href$=".png"],a[href$=".gif"]').colorbox({
    transition:'elastic',
    rel:'gallery',
    opacity:.45,
      fixed: true,
      maxWidth: '95%',
      maxHeight: '95%'
  });

//End!
});

Notice the opening function jQuery(document).ready(function($){ this is the important part here, all your script calls, for jQuery plugins or any custom jQuery should be placed between this function. Basically it just makes the dollar sign used as shorthand for jQuery, play nice with WordPress.

That’s it!

Leave a Comment

To preserve code added to a comment you can wrap your code in short tags
by using [square brackets]:

  1. PHP use - [php] <?php code here ?> [/php]
  2. CSS use - [css] #code-here {} [/css]
  3. HTML use - [html] <div> code here </div> [/html]
  4. JS use - [js] $(".codeHere") [/js]