Are you looking to add JavaScript code to a specific page? Unfortunately, WordPress does not allow you to add JavaScript code by default to specific pages. In this article, we are going to show how you can add JavaScript code to specific pages in WordPress using two methods – with the help of a plugin or by adding code manually.
Adding JavaScript code with the help of a plugin
If you are new to WordPress then using a plugin is the best way to add JavaScript code to your website. Header Footer Code Manager by 99 Robots is a great plugin for the task. It has over 200,000 active installations on the WordPress plugin store and provides an easy dashboard to add JavaScript code to specific pages and posts. Follow the below steps to add JavaScript code to specific pages using this plugin:
- Install and activate the plugin.
- Once the plugin is activated a menu item by the name of HFCM will be added to your admin navigation sidebar.
- Navigate to HFCM -> Add New.
- In Snippet Name enter a name for the snippet,
In Snippet Type select Javascript,
In Site Display dropdown select Specific Pages option,
In Page List dropdown select the page you want to add the JS code on,
You can leave the rest options to default.
- Now scroll down to the Snippet/Code box and add your JavaScript code in that box.
- Once done, click on the Save button at the bottom. Your JS code will now work on that specific page.
Adding JavaScript code without a plugin using code
Using a plugin for everything is not the recommended way. They often slow down your website and add unnecessary code to the web pages. Follow the below steps to add JavaScript code to specific pages without the help of a plugin.
- Navigate to Appearance -> Theme Editor from your admin dashboard.
- Select the functions.php file from Theme Files list.
- Add the below code in the edit box of functions.php file to add Javascript code to specific pages.
function js_code_page() { if (is_page ('3')) { ?> <script type="text/javascript"> // Add your JavaScript code here </script> <!--?php } } add_action('wp_head', 'js_code_page'); [/php] In the above code replace 3 with Page ID for the specific page you want the JS code to run on. You can also add JS code to specific posts using the below code. [php] function js_code_post() { if (is_single ('5')) { ?--> <script type="text/javascript"> // Add your JavaScript code here </script> <!--?php <br ?--> } } add_action('wp_head', 'js_code_post');
Here replace 5 with your Post ID.
5. Once done, click on the Update File button at the bottom.Conclusion
You may often require to add JavaScript code to your pages. With the help of the above tutorial you will be able to add the code easily in your WordPress website using a plugin or without one.