This tutorial will walk you through creating a custom javascript file and loading it on your site.
1. Create a child theme
While it isn’t strictly necessary, it’s almost always a good idea to make your customizations in a child theme. If you don’t and your parent theme gets updated (like most non-custom themes will), then you’ll lose all your work when you update. So make sure to set up a child theme.
Not sure how to set up a child theme? Read Smashing Mag’s How to Create and Customize a WordPress Child Theme.
Don’t want to be bothered with setting it up manually? Use the Child Theme Configurator Plugin to generate it for you.
Do not forget to activate the child theme after creating it.
2. Create your script
In your child theme directory (wp-content/themes/your-child-theme
), create a javascript file. We’ll call it shiftnav-custom.js
. So the file will live at wp-content/themes/your-child-theme/shiftnav-custom.js
. Of course, you can customize this as you see fit, just adjust the following code accordingly.
Open up the file and add your code!
Most scripts should run after the document is ready, so add your code inside this wrapper:
jQuery(function($) { //Your code goes here });
This example code prints out the number of ShiftNav instances loaded on the page:
jQuery(function($) { console.log( 'ShiftNavs: ' + $('.shiftnav').length ); });
3. Load your script
So far you’ve created your script. Now you need to tell WordPress to load it on the page.
To do this, add this code in your child theme’s functions.php
.
function my_custom_assets(){ //Get the active theme directory $dir = trailingslashit( get_stylesheet_directory_uri() ); //Enqueue the custom script, which is located in the active theme directory wp_enqueue_script( 'shiftnav-custom-js' , $dir.'shiftnav-custom.js' , array( 'shiftnav' ) , false , true ); } add_action( 'wp_enqueue_scripts' , 'my_custom_assets' , 20 );
This code tells WordPress to load the shiftnav-custom.js file found in your active theme in the footer of your site, with a dependency on the ShiftNav javascript (so that the ShiftNav API functions should be available if you want to use them).
That’s it! I suggest starting with a simple console.log() to test if your script is being loaded and run.