Wordpress - How to add a javascript snippet to the footer that requires jQuery
The easiest way to do this is actually a combination of wp_enqueue_script
and the footer actions that Saif and v0idless already referenced. I frequently use jQuery in my themes and plugins, but I put all of the other scripts in the footer as well.
The best way to actually queue things up would be this:
function myscript() {
?>
<script type="text/javascript">
if ( undefined !== window.jQuery ) {
// script dependent on jQuery
}
</script>
<?php
}
add_action( 'wp_footer', 'myscript' );
function myscript_jquery() {
wp_enqueue_script( 'jquery' );
}
add_action( 'wp_head' , 'myscript_jquery' );
But this code snipped assumes that you're the one queueing the script, i.e. you're doing this in your own plugin or theme.
At the moment, there is no way to add an in-line script to the WordPress footer and also load it with dependencies. But there is an alternative, if you're willing.
The alternative
When WordPress works with scripts, it loads them internally to an object to keep track of them. There are essentially 3 lists inside the object:
- registered
- queue
- done
- to_do
When you first register a script with wp_register_scripts()
it's placed in the registered list. When you wp_enqueue_script()
the script, it's copied to the queue list. After it's been printed to the page, it's added to the done list.
So, rather than queueing your footer script to require jQuery, you can document that it needs to use jQuery and just check programatically to make sure jQuery is loaded.
This uses wp_script_is()
to check where the script is listed.
function myscript() {
if( wp_script_is( 'jquery', 'done' ) ) {
?>
<script type="text/javascript">
// script dependent on jQuery
</script>
<?php
}
}
add_action( 'wp_footer', 'myscript' );
You might be able to use this same code to force jQuery to load in the footer as well, but I haven't tested that ... so your mileage my vary.
Since wordpress 4.5 you can add inline script by wp_add_inline_script()
. To add a javascript snippet to the footer that requires jQuery, this code helps you
function enqueue_jquery_in_footer( &$scripts ) {
if ( ! is_admin() )
$scripts->add_data( 'jquery', 'group', 1 );
}
add_action( 'wp_default_scripts', 'enqueue_jquery_in_footer' );
function theme_prefix_enqueue_script() {
if(!wp_script_is('jquery', 'done')) {
wp_enqueue_script('jquery');
}
wp_add_inline_script( 'jquery-migrate', 'jQuery(document).ready(function(){});' );
}
add_action( 'wp_enqueue_scripts', 'theme_prefix_enqueue_script' );
wp_add_inline_script with wordpress jquery