×

Noctua Ideas | Micah Neal

jQuery & WordPress

When using jQuery in WordPress there are a couple of things to be aware of:

jQuery is already bundled with WordPress!

We just need to enqueue it. Most simply we can place this in our functions.php file:

wp_enqueue_script("jquery");

Personally I like to load all of my javascript in a function to keep it nice and neat. Hooray for encapsulation! Example:

function theme_js() {
  wp_enqueue_script( 'jquery' );
	wp_register_script( 'bootstrap-js', get_template_directory_uri() . '/js/bootstrap.min.js', array('jquery'), NULL, true );
	wp_enqueue_script( 'bootstrap-js' );
}
add_action( 'wp_enqueue_scripts', 'theme_js' );
    

I would like to note that in the wp_register_script function that the third paramater inidcates that jQuery should be loaded before bootstrap-js. Please look at the handy dandy WordPress codex if you need help with the functions above.

I see errors

We have jQuery working, but hold on a minute my console is so red with errors it looks like it’s bleeding!

This is due to the fact that WordPress loads jQuery in compatibility mode, in an effort to prevent conflicts with other libraries such as MooTools. Which means that the familiar $ we know and love is not available to us! Instead we should use jQuery any place that we would typically use a $, as $ is simply a shorthand alias for jQuery.

Despair not!

For we can wrap our jQuery to again have access to our beloved $. Inside our javascript file if the file is being loaded in the footer, as it probably should, we can wrap our code with:

(function($) {
   // Insert all of your fancy code here!
})( jQuery );
    

However if you’re stubborn and just have to load your javascript in the head, you can use this:

jQuery(document).ready(function( $ ) {
   // Insert all of your fancy code here!
});
    

Further caveat:

there doesn’t appear to be a fantastic way to load a file using wp_register_script & wp_enqueue_script ( as you should! ) containing jQuery not already optimized for compatibility mode without first altering the file as detailed above