Dougie Hunt

Beginners Guide to Javascript for WordPress

WordPress Article

πŸ‘Ύ 3,170 Views

⭐ Updated 28 January 2024

πŸ’₯ Published 28 January 2024

Beginners Guide to Javascript for WordPress

If you are having a nightmare trying to figure out how to add Javascript to your WordPress install then here is a quick guide. A no-nonsense beginners guide to enqueuing javascript for WordPress.


Don’t be frightened by wp_enqueue. It comes it two varieties that you need to know: (1) wp_enqueue_script and (2) wp_enqueue_style.

wp_enqueue_script loads javascript. wp_enqueue_style loads stylesheets.


In this guide, we are only going to look at the former, wp_enqueue_script, which is the correct way to load javascript in WordPress.

Example of WP_Enqueue_Script

In the example below we are loading a javascript file called ‘linktrack.js’ located in the ‘js’ folder:

wp_enqueue_script( 'linktrack', get_template_directory_uri() . '/js/linktrack.js' );

The file is located in two parts: (1) ‘get_template_directory_uri() and (2) ‘/js/linktrack.js’.

The function is named as ‘linktrack’.

Step-by-step guide to loading Javascript in WordPress

Ok, now we are ready to proceed with the guide on how to correctly loading javascript in WordPress.

Step 1: Functions.php

You first need to locate the functions.php file. It is worth duplicating this file to custom-functions.php before making any changes so that if you make any mistakes you can quickly restart with a copy of the original.

I also recommend not editing the functions.php file on a live site as this will corrupt your install. Best to make any changes on a development or local install.

Step 2: Uploading your Javascript file

First locate your ‘js’ folder in your theme folder. If you don’t have one, quickly create a folder and name it ‘js’.

In that folder upload your javascript file. Remember to name it with the extensions ‘.js’. For example ‘linktrack.js’.

Step 3: Editing your functions.php file

Open your functions.php file and add the wp_enqueue function:

* Enqueue scripts and styles.
function theme_scripts() {
wp_enqueue_script( 'linktrack', get_template_directory_uri() . '/js/linktrack.js' );
add_action( 'wp_enqueue_scripts', 'theme_scripts' );

Now you just need to replace the highlight parts above with your function name and the file name.

That’s it. Just refresh your website and open page source and you’ll see your javascript file correctly loading in your site’s header. For more information visit the WordPress Codex.


Take part in the discussion

Discussion about Beginners Guide to Javascript for WordPress article, if you have any questions, comments or thoughts then get leave a reply.

WordPress Powered By