WordPress Child-Themes 16: Adding JavaScript

WordPress Child-Themes 16: Adding JavaScript

September 12, 2019 3 By Bernardo Ryan


How do I add my own jQuery scripts? In some cases, plain HTML and CSS is not enough to build the design and functionality of your site. Often, you want to add some JavaScript to the mix. WordPress supports jQuery by default. As a matter of fact, the latest jQuery library is included in the WordPress version that you have already installed. So, it’s easy to add jQuery scripts or jQuery plugins to the site. Let’s say, for example, you want to add something that’s called superfish. It’s a script to add some cool animation to your menus. To add any jQuery script to your theme, you should follow the proper way to do it, instead of just hacking it into the header.php script. This will ensure, that all the scripts will be called in the correct order. In this case, I have added an action for wp_enqueue_scripts to my setup function. It will call the function enqueue_my_scripts to register all the scripts in the proper order. I have also added an action for wp_print_scripts which will fire when the pre-defined scripts shall be printed on the browser page, usually in the head section of the page. Before I implement these I have to copy my scripts somewhere into my theme folder. I’m using a sub-directory js where I’ve included the scripts superfish.js and hoverIntent.js. I have also added a custom script, that will enable superfish on my main navigation menu. Now I implement the function enqueue_my_scripts where I register all the jQuery scripts that I want to use in my theme. To do this, I use the WordPress function wp_register_script. First parameter is a short handle to identify the script. Second is the path and file name of the script. Third is an array of handles for all scripts that need to be loaded beforehand. In this case, we make sure that jquery will be loaded first. This method makes it easy, to sort out all the necessary scripts before any output on the browser page. So you can add and remove scripts before they are called up in the browser. The other action hook will fire when the scripts are ready to be inserted on the page. Here we will just call wp_enqueue_script for each registered script. In this case, we just need to call it for ‘custom’, because it contains proper dependencies to the other scripts needed. As you can see from the HTML source code on the page, the scripts are called in their proper order. First jQuery Then, later, superfish and hoverintent and the custom script last.