Do you want to learn how to properly add JavaScripts and CSS stylesheets in WordPress?
Many DIY users often make the mistake of directly calling their scripts and stylesheets in plugins and themes. Based on our experience, this can cause multiple issues later on.
In this article, we’ll show you how to properly add JavaScript and stylesheets in WordPress. This will be particularly useful for those who are just starting to learn WordPress theme and plugin development.
Common Mistake When Adding Scripts and Stylesheets in WordPress
Many new WordPress plugin and theme developers make the mistake of directly adding their scripts or inline CSS into their plugins and themes.
Some mistakenly use the wp_head
function to load their scripts and stylesheets.
<?php
add_action('wp_head', 'wpb_bad_script');
function wpb_bad_script() {
echo 'jQuery goes here';
}
?>
While the above code may seem easier, it is the wrong way of adding scripts in WordPress, and it leads to more conflicts in the future.
For example, if you load jQuery manually and another plugin loads jQuery through the proper method, then you have jQuery being loaded twice. If it is loaded on every page, then this will negatively affect WordPress speed and performance.
It is also possible that the two are different versions which can also cause conflicts.
That being said, let’s take a look at the right way of adding scripts and stylesheets.
Why Enqueue Scripts and Styles in WordPress?
WordPress has a strong developer community. Thousands of people from around the world develop themes and plugins for WordPress.
To make sure that everything works properly, and no one is stepping on another’s toes, WordPress has an enqueuing system. This system provides a programmable way of loading JavaScripts and CSS stylesheets.
By using wp_enqueue_script and wp_enqueue_style functions, you tell WordPress when to load a file, where to load it, and what are its dependencies.
This system also allow developers to utilize the built-in JavaScript libraries that come bundled with WordPress rather than loading the same third-party script multiple times. This reduces page load time and helps avoid conflicts with other plugins and themes.
How to Properly Enqueue Scripts in WordPress?
Loading scripts properly in WordPress is very easy. Below is an example code that you would paste in your plugins file, in your theme’s functions.php file, or in a code snippets plugin to properly load scripts in WordPress.
?php
function wpb_adding_scripts() {
wp_register_script('my_amazing_script', plugins_url('amazing_script.js', __FILE__), array('jquery'),'1.1', true);
wp_enqueue_script('my_amazing_script');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );
?>
Explanation:
We started by registering our script through the wp_register_script()
function. This function accepts 5 parameters:
- $handle – Handle is the unique name of your script. Ours is called “my_amazing_script”
- $src – src is the location of your script. We are using the plugins_url function to get the proper URL of our plugins folder. Once WordPress finds that, then it will look for our filename amazing_script.js in that folder.
- $deps – deps is for dependency. Since our script uses jQuery, we have added jQuery in the dependency area. WordPress will automatically load jQuery if it is not being loaded already on the site.
- $ver – This is the version number of our script. This parameter is not required.
- $in_footer – We want to load our script in the footer, so we have set the value to be true. If you want to load the script in the header, then you would make it false.
After providing all the parameters in wp_register_script
, we can just call the script in wp_enqueue_script()
which makes everything happen.
The last step is to use wp_enqueue_scripts action hook to actually load the script. Since this is an example code, we have added that right below everything else.
If you were adding this to your theme or plugin, then you can place this action hook where the script is actually required. This allows you to reduce the memory footprint of your plugin.
Now some might wonder why are we going the extra step to register the script first and then enqueuing it? Well, this allows other site owners to deregister your script without modifying the core code of your plugin.
Properly Enqueue Styles in WordPress
Just like scripts, you can also enqueue your stylesheets. Look at the example below:
<?php
function wpb_adding_styles() {
wp_register_style('my_stylesheet', plugins_url('my-stylesheet.css', __FILE__));
wp_enqueue_style('my_stylesheet');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_styles' );
?>
Instead of using wp_enqueue_script
, we are now using wp_enqueue_style
to add our stylesheet.
Notice that we have used wp_enqueue_scripts
action hook for both styles and scripts. Despite the name, this function works for both.
In the examples above, we have used plugins_url
function to point to the location of the script or style we wanted to enqueue.
However, if you are using the enqueue scripts function in your theme, then simply use get_template_directory_uri()
instead. If you are working with a child theme, then use get_stylesheet_directory_uri()
.
Below is an example code:
<?php
function wpb_adding_scripts() {
wp_register_script('my_amazing_script', get_template_directory_uri() . '/js/amazing_script.js', array('jquery'),'1.1', true);
wp_enqueue_script('my_amazing_script');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );
?>
We hope this article helped you learn how to properly add JavaScript and styles in WordPress. You may also want to study the source code of the top WordPress plugins for some real life code examples or check out our guide on how to easily add JavaScript in WordPress posts or pages.
If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.
Mrteesurez
This post is a bit technical but l love it as I am into WordPress development, it made me learn more to use to use PHP and add stylesheet and scripts in a proper way. The best practice is given in this article so that there will be no conflict between codes in the future.
Schroedingers Katze
Cheers, thanks for sharing! Great explanation.
WPBeginner Support
You’re welcome
Admin
Jean-Michel
Hi there,
I followed what is said here but now I get an empty white page on my web site. Could someone give me a hint ?
Thanks
WPBeginner Support
It sounds like you either copied the code incorrectly or it had an issue with something on your site. You can remove the code using: https://www.wpbeginner.com/beginners-guide/how-to-use-ftp-to-upload-files-to-wordpress-for-beginners/
If you added it manually, otherwise you could use:
https://www.wpbeginner.com/wp-tutorials/how-to-fix-the-wordpress-white-screen-of-death/
Admin
Orhan
This article was very useful to me. Thank you.
Mark
Typical article that makes you even more confused after than before…
Zaved Hossain
This is nice, though my usual practice is to add wp_enqueue_script/style in a single line without registering. Coders need to be careful about the parameters, perhaps a little explanation of that would be helpful. For example, the different versions of jquery (your jquery script may require different version than the wordpress’) and where to add it (header or footer which is determined by the true/false parameter). The jquery script needs to be added in the header, (hence a ‘false’ needs to be passed as the param value), otherwise it may not work.
Hansjörg Leichsenring
There are often a lot of style.css.
How can I ensure the correct load-order with enque and make sure, that the child css is loaded last?
Cheers from Germany
Hansjörg
Carlos Araya
How do I pass empty parameter to register_script? I want to make sure that they script is loaded at the bottom of the page but can’t find information whether this is the default behavior or not
Kerry Beeher
Bonjour,
Thank you for your excellente resource. Merci !!!
I am little novice and just begin my journey to learn PHP and how WordPress use wp_enqueue_script and wp_register_script to add JavaScript and CSS.
I use this free plugin called Easy Code Manager to help run through your exemples:
however I am not sure if this is right plugin to use.
I read before that it is not the best idea to modifier code in functions.php so I wonder if this is ok to do?
Will it not get change on a theme update?
Sorry for question, I still learn WordPress.
Merci,
Kerry
Vaibhav Bansal
I want to add an Amazon Ad
I tried to add it in text widget, but it shows blank.
Below is the code-
This is my site-
Help me. How do I add js on my site?
WPBeginner Support
Hi Vaibhav,
Please check out our list of ad management plugins for WordPress. You can use these plugins to display ads on your WordPress site without editing your theme files.
Admin
pradyumna
i have inserted a javascript using this plugin but now i have to remove it, i have tried uninstalling and deactivating the plugin but the javascript still executes
Vijay.Rajpal
Hello Sir,
I am using esteem theme and I wanted to add some javascripts functionality to my website like lightbox. I have created a child theme and the code are as follows. in the functions.php.
and I am getting an error:-Parse error: syntax error, unexpected '{' in E:\InstantWP_4.5\iwpserver\htdocs\wordpress\wp-content\themes\esteem-child\functions.php on line 18
Please Help I am using sublime as my text editor.
Please Help!!!!!
WPBeginner Support
There is an unexpected { in the code. Go to the line 18 of your functions file and then carefully study the code. You may have forgotten some tiny code like a missing ;
Admin
Pramod
hello…..
i m adding .js file in js directory of wordpress and gives its reference of it in funcation.php
but its not working
wp_enqueue_script( ‘any-navigation’, get_template_directory_uri() . ‘/js/menu.js’);
Bobbie
Thanks so much! I’ve been trying to add a custom .js file but this is the first explanation that the register_script was needed.
colkav
Hey, great tutorial. I’m having an issue adding a Google Analytics related javascript, as described here:
I’ve put the script in my child theme’s ‘js’ folder (having first stripped the html from the code).
When i load up the page I keep getting the error :
ReferenceError: Can’t find variable: ga
(anonymous function)myscript.js:6
…and it just dawned on me that maybe I need to add ‘analytics.js’ as a dependency!
Does that sounds right? And if so, how would I add analytics as a dependency for my script? I’ve tried experimenting here to no avail
Shoaib
Is there any Plugin for the same … i am newbie and can’t play with codes … Plz Help me Sir
xavi
Hi.
thanks for this amazing post tutorial! But when you say “where to upload the script” you just can define head or footer (in all entire webpages!)? Could you define an especific page to load it? I just need it in one. Thanks for advance and keep working! Cheers.
technofranchise
I want to use JavaScript or JQuery in my WordPress site. Any ideas?
Skye Barcus
I am a total novice at js but do know html. I want to put this on a wordpress page:
Basically, it’s a widget to join a GoToMeeting. This works if you just throw it into the body of an html page, but in Wordpress, it gets supressed.
Can you give me a “For Dummies” version of how to make this work?
Tyler Longren
On the style loading piece, on line 6, wp_register_script, should be wp_register_style I believe.
WPBeginner Support
Tyler, no this will work too.
Admin
Pedro de Carvalho
why you chose to use _script instead?
Pali Madra
I would also like to know why use _script and not _style? Are there any benefits or will both work therefore either can be used?
Dejan
I really like you site it is full of useful tips, however looks like you are not doing it “Properly” for CSS enqueue even though your title say that way :=) The right way would be :
wp_register_style( ‘my-css-style’, get_template_directory_uri() . ‘/css/style.css’, array(), ‘1.0’, ‘all’ );
wp_enqueue_style( ‘my-css-style’ );
Keep up the good work… Cheers!
Adrian Zumbrunnen
Thanks for the effort you put into this. It just feels wrong to have wp_enque_script for loading stylesheets. Wordpress could eventually spit out script instead of the stylehseet syntax for it.
Do you really embed that way?
WPBeginner Support
This tutorial shows how to load JavaScript and stylesheet files for your themes or plugins in WordPress. If by Embed you meant how we display code in articles, then we use Syntax Highlighter plugin for that.
Admin
oiveros
hi i’m kind of new on the wordpress theming , and reading about these topic, i wanted to ask you about something related to these . If i want to update the jquery library link how do i do it or where do i find the link i been trying to do it but i can’t find it. Thank you in advanced for your help
WPBeginner Support
If by updating jquery library link, you mean to add jquery from Google’s library. WordPress comes packed with jquery and to load it in your theme use this line in your theme:
<?php wp_enqueue_script('jquery'); ?>
Admin
oiveros
okey so if i want to have the latest jquery, i just use that line?, because somebody told me to use a plugin just for that, but i wanted to learn how to do it without a plugin
oliveros
Thank you for your answer, i found the post related to that issue here in your site.
Mark
Thanks so much for this tut.
Elliott Richmond
Useful Syed, thanks.
I recently had an issue loading a css file using _underscore as a framework, although the stylesheet was called mycustomstyles.css the theme was calling mycustomstyles.css?ver=xx and the theme wasn’t loading the file because of the naming of the file by appending ?ver=xx to the end of the name.
Is that something to do with $ver default?