How do I add a simple jQuery script to WordPress?

Do you want to know the best way to add you script be it jQuery script or any other javascript ?

Well! many times we can run into a situation where we need to add script to our WordPress site to add some additional functionality or for any other good reason. So, if you are a beginner or new to WordPress development then most of the code you will find at WordPress Codex will seem completely rocket science to you. Its hard to figure out the that where to use what code and many questions arises like, if this code should go in functions.php, header.php, footer.php or somewhere else.

I am explaining a simple process to add your script to your WordPress website.

If you have already started learning WordPress or you are a expert then you are off-course aware of the fact that functions.php is the file which holds most of our functions and it loads every time WordPress executes any pages. So, what we are going to do is create in filename.js in js directory of you theme. This filename.js should contain your script.
Your content for filename.js file should look like the code below :

// if you are using jQuery then always use jQuery in place of $ in jQuery Code
jQuery(document).ready(function($) {
 alert("script added!!");

Now that we have created our script file filename.js, we just need to connect it to our WordPress. Open your functions.php file and add the following code :

add_action( 'wp_enqueue_scripts', 'addmyscript' );
function addmyscript() {
        'yourscript', // name your script so that you can attach other scripts and de-register, etc.
        get_template_directory_uri() . '/js/filename.js', // location of your script file
        array('jquery') // this array lists the scripts upon which your script depends

wp_enqueue_scripts add script to every page of WordPress.
Feel free to comment to ask for better understanding or code suggestions.

Leave a Comment