So as recommended, I enqueue my scripts in the function.php file instead of in the head like the following example:
function bok_scripts() {
wp_enqueue_script( 'custom', get_template_directory_uri() . '/js/custom.js' );
}
add_action( 'wp_enqueue_scripts', 'bok_scripts' );
The problem is that this JavaScript won't work unless I add jQuery to the head using the usual:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The problem I always run into, though, is that WordPress automatically loads a version of jQuery using the wp_head();
from the wp-admin/includes directory. Because the jQuery is getting loaded 2x, it breaks some of the code. For instance the following will throw a 'This is not a function ($)' error:
$(window).load(function(){
$('#modal-notices').modal('show');
});
Does anyone know how to overcome this? I've tried a bunch of stuff, but all that seems to work is deleting the jQuery from the wp-admin/includes directory. Obviously, though, that isn't a proper fix.
The first thing you need to do is declare jQuery as a dependency of your script so that WordPress knows to load it.
To do that change:
To:
There's a second issue you're facing and that's jQuery in WordPress loads in noConflict mode. This means the global '$' shortcut is no longer available. Here's some more information: http://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_Wrappers
To get your script working change:
To:
Finally be sure to remove any jQuery scripts you've added directly to the header/footer instead of enqueueing.