A plugin I’m working on requires jquery to be loaded before the content is processed. Some stock themes, like 2010, 2011 and 2012 (I believe) put the JS in the footer.
How can I force the scripts to be loaded in the header (I will notify users of the plugin that the plugin requires this)?
The normal behavior of
wp_enqueue_script
is to put the script output into the head section, the parameter$in_footer
is optional and defaults tofalse
. So, you can load jQuery with your plugin into the head and, assumed your dealing with well programmed themes/plugins, it won’t load again, becausewp_enqueue_script
prevents this by default – additional information about that here.The third parameter of wp_enqueue_script() allows you declare dependencies for the script you’re enqueueing, i.e. what other scripts are required for them to run.
That way, no matter where any theme, plugin, whatever loads jquery, your script will always load later, assuming they follow best practices as well and don’t deregister it.
In your shortcode handler You could return an HTML placeholder element or JavaScript variable, and then hook onto
wp_footer
with another function that “runs” jQuery.Accoriding to the WP Reference for wp_enqueue_scripts
The last parameter is responsible for where the script will be loaded.
There are some snags which can change his behaviour !
Try to find and comment/remove this lines from your function.php file
The purpose of this six actions is to automatically move JavaScript code to page footer making the last parameter from wp_enqueue_scripts unuseful!
If this actions can not be removed, then you can change the priorities of them. From 5 to 9999 per example. Play with the priorities to find the right one for you.
You also need to check if the are some dependencies specified in the $deps array.Witch gone force the script to be loaded after resolving them.
Don’t try any dirty hacks, it is a bad practice
Happy coding
First, dequeue the jQuery enqueued by the theme. Then enqueue it again.
You might need to play with the priority to get what you need.