How to Add Custom JavaScript to a Specific Page in WordPress

In this tutorial I will share a simple technique to add custom JavaScript to a specific Page in WordPress. The best part is that we don’t need to make any edits to the templates files or the functions.php file.

The Concept

The Concept behind this tutorial is quite simple. We will make use of Custom Fields to add custom js. Here is what we will be doing

  • We will first create a custom field to hold the JavaScript code
  • We will then simply output the value of custom field on the respective Page

Simple, isn’t it? Lets start!!

1. Create a Custom Field

Go to the Page Editor Screen and create a new custom field. Now paste the JS code in the newly created custom field. Refer to the following screenshot

Add js to custom field

 

In case you cannot see the Custom field box , just enable it from the Screen Options. Refer to this tutorial.

2. Now include JS in the Page

We now need to include the JS which we pasted in the custom field.  We will utilize the Code Snippets plugin for this.  The Code Snippets plugin lets run custom code snippets without editing the functions.php file.

Install the Code Snippets plugin. Copy Paste the following snippet and activate it.

function load_custom_js() {

	global $post; 
	$postid = $post->ID;
	
	if ($postid == '77') 
	{
		$myjs = get_post_meta( 77, 'my_custom_js', true );
		echo $myjs; 
	}
}


add_action( 'wp_enqueue_scripts', 'load_custom_js' );

The above snippet simply outputs the value stored in my_custom_js field. Take note that we also check the id of the Page which is loaded.

3. Add JS to Multiple Pages

We can also add JS to multiple Pages, we simply need to check for multiple post ids. Here is the modified snippet

function load_custom_js() {

	global $post; 
	$postid = $post->ID;
	
	if ($postid == '77' or $postid == '20' or $postid == '28') 
	{
		$myjs = get_post_meta( 77, 'my_custom_js', true );
		echo $myjs; 
	}
}


add_action( 'wp_enqueue_scripts', 'load_custom_js' );

Points to Note

  • You can use this technique to add Custom CSS
  • You can use this technique to add scripts to specific custom post types

 

Did you enjoy this article?
We regularly publish WordPress related Tutorials and Tips on this blog. Signup today and receive free updates straight in your inbox.
I agree to have my personal information transfered to Mad Mimi ( more information )
About Ankit

Founder of SpiceWp. We share useful Wordprss Tips and Tricks.

I have also released 17 Wordpress Plugins till date .

I regularly publish Wordpress related Tutorials and Tips on this blog.
If you like the content then consider subscribing to the blog here.

Speak Your Mind

*