I’m creating a plugin for WordPress, when I use below code in plugin main file it load js in <head>
, it works fine.
wp_enqueue_script ( 'custom-script', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-v4- rtl/4.6.0-1/js/bootstrap.bundle.min.jsf');
but when I use it inside a function (for example show_form()
):
function show_form()
{
wp_enqueue_script ( 'custom-script', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-v4- rtl/4.6.0-1/js/bootstrap.bundle.min.js');
require_once 'form.php';
}
it loads script at the bottom of the page (before </body>
).
what’s wrong with my code?
I need to enqueue script inside the <head>
only when my form.php loads.
I know I can load script directly in form.php but i need to load script via wp_enqueue_script
2
Answers
When
show_form()
is called, you’re already too far along in the execution path to go back and insert code into the head section.Any JS you want to load should be fired on the
wp_enqueue_scripts
action.wp_enqueue_script()
can be used to determine whether code loads in the head or footer of the site.If there are two points at which you can insert code using
wp_enqueue_script()
and it’s being inserted into the footer even though you haven’t specified that, it’s because you’re calling enqueue script after the head scripts have been inserted.You need to either determine whether a form is shown on the page earlier in the loading of the page or use your JS in a way that can be supported across the site.
Example:
You’re not following best practices.
Any script should be added to the WordPress firing sequence via
wp_enqueue_scripts()
firing hook.Furthermore, when you take a look at the
wp_enqueue_script()
function CODEX page you can see that it accept a bunch of arguments including a$in_footer
variable.As a reminder you can also set a
$deps
variable.The proper way to enqueue for example Bootstrap
4.6.0
(in your case) is to add a dependency to Jquery and load both of them in the footer, not the header. As most of the time any related js action are unnecessary before the DOM as been fully loaded. In the following example I will be enqueuing both Jquery and Bootstrap in the footer, tho you can alway changetrue
tofalse
.As you’re using a CDN you should be checking is the source is available and have a fallback locally waiting. you should also include integrity and crossorigin attributes.