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
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
The post How to Add Custom JavaScript to a Specific Page in WordPress appeared first on Spoontalk WP Blog.