WPBeginner

Beginner's Guide for WordPress

  • Blog
    • Beginners Guide
    • News
    • Opinion
    • Showcase
    • Themes
    • Tutorials
    • WordPress Plugins
  • Start Here
    • How to Start a Blog
    • Create a Website
    • Start an Online Store
    • Best Website Builder
    • Email Marketing
    • WordPress Hosting
    • Business Name Ideas
  • Deals
    • Bluehost Coupon
    • SiteGround Coupon
    • WP Engine Coupon
    • HostGator Coupon
    • Domain.com Coupon
    • Constant Contact
    • View All Deals »
  • Glossary
  • Videos
  • Products
X
☰
Beginner's Guide for WordPress / Start your WordPress Blog in minutes
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

WPBeginner» Blog» Tutorials» How to Easily Add JavaScript in WordPress Pages or Posts (3 Methods)

How to Easily Add JavaScript in WordPress Pages or Posts (3 Methods)

Last updated on March 29th, 2019 by Editorial Staff
210 Shares
Share
Tweet
Share
Pin
Free WordPress Video Tutorials on YouTube by WPBeginner
How to Easily Add JavaScript in WordPress Pages or Posts (3 Methods)

Do you want to add a JavaScript in your WordPress pages or posts? Sometimes you may need to add a JavaScript code to the entire website or into specific pages. By default, WordPress does not let you add code directly in your posts. In this article, we will show you how to easily add JavaScript in WordPress pages or posts.

How to easily add JavaScript in WordPress posts and pages

What is JavaScript?

JavaScript is a programming language that runs not on your server but on the user’s browser. This client-side programming allows developers to do a lot of cool things without slowing down your website.

If you want to embed a video player, add a calculator, or some other third-party service, then you will be often asked to copy and paste a JavaScript code snippet into your website.

A typical JavaScript code snippet may look like this:

<script type="text/javascript"> 

// Some JavaScript code

</script>

<!-- Another Example: --!>  

<script type="text/javascript" src="/path/to/some-script.js"></script>

Now, if you add a javascript code snippet to a WordPress post or page, then it will be deleted by WordPress when you try to save it.

That being said, let’s see how you can easily add JavaScript in WordPress pages or posts without breaking your website.

Method 1. Add JavaScript Site-Wide Using Insert Headers and Footers

Sometimes you will be asked to copy and paste a JavaScript code snippet into your website to add a third-party tool. These scripts usually go to the head section or at the bottom before the </body> tag of your website. This way the code is loaded on every page view.

For example, Google Analytics installation code needs to be present on every page of your website, so it can track your website visitors.

You can add such code to your WordPress theme’s header.php or footer.php files. However, these changes will be overwritten when you update or change your theme.

That’s why we recommend using a plugin to load javascript on your site.

First, you need to install and activate the Insert Headers and Footers plugin. For more details, see our step by step guide on how to install a WordPress plugin.

Upon activation, you need to visit Settings » Insert Headers and Footers page. You will see two boxes, one for the header and the other for the footer section.

Insert Headers and Footers plugin settings

You can now paste the JavaScript code you copied to one of these boxes and then click on the save button.

Insert Headers and Footers plugin will now automatically load the code you added on every page of your website.

Method 2. Adding JavaScript Code Manually Using Code

This method requires you to add code to your WordPress files. If you haven’t done this before, then please see our guide on how to copy and paste code in WordPress.

First, let’s take a look at how to add code to your WordPress site’s header. You will need to add the following code to your theme’s functions.php file or a site-specific plugin.

function wpb_hook_javascript() {
    ?>
        <script>
          // your javscript code goes
        </script>
    <?php
}
add_action('wp_head', 'wpb_hook_javascript');

Adding JavaScript to a Specific WordPress Post or Page Using Code

Let’s suppose you only want to load this javascript on a specific WordPress post. To do that, you will need to add conditional logic to the code. Take a look at the following example:


function wpb_hook_javascript() {
  if (is_single ('16')) { 
    ?>
        <script type="text/javascript">
          // your javscript code goes here
        </script>
    <?php
  }
}
add_action('wp_head', 'wpb_hook_javascript');

If you take a closer look at the code above, you will see that we have wrapped javascript code around conditional logic to match a specific post ID. You can use this by replacing 16 with your own post ID.

Now, this code would work for any post type except for pages. Let’s take a look at another example except this one will check for a specific page ID before adding the javascript code to the head section.

function wpb_hook_javascript() {
  if (is_page ('10')) { 
    ?>
        <script type="text/javascript">
          // your javscript code goes here
        </script>
    <?php
  }
}
add_action('wp_head', 'wpb_hook_javascript');

Instead of is_single, we are now using is_page to check for page ID.

We can use the same code with slight modification to add javascript code to your site’s footer. Take a look at the following example.

function wpb_hook_javascript_footer() {
    ?>
        <script>
          // your javscript code goes
        </script>
    <?php
}
add_action('wp_footer', 'wpb_hook_javascript_footer');

Instead of hooking our function to wp_head, we have now hooked it to wp_footer. You can also use it with conditional tags to add Javascript to specific posts or pages.

Method 3. Adding Javascript Code Inside Posts or Pages Using Plugin

This method will allow you to add code anywhere inside your WordPress posts and pages. You will also be able to select where in the content you want to embed the javascript code.

First, you need to install and activate the Code Embed plugin. For more details, see our step by step guide on how to install a WordPress plugin.

Upon activation, you need to edit the post or page where you want to add the javascript. On the post edit page, click on the ‘Screen Options‘ button and check the ‘Custom Fields’ option.

Show custom fields meta box

Now scroll down and below the post editor, you will see the ‘Custom Fields’ metabox where you need to click on the ‘Enter new’ link.

Add a new custom field

The custom field name and value fields will now appear.

You need to provide a name for the custom field with a CODE prefix (for example, CODEmyjscode) and then paste the javascript code in the value field.

Adding a JavaScript code to a custom field

Don’t forget to click on the ‘Add Custom Field’ button to save your custom field.

Now you can use this custom field to embed the JavaScript code anywhere in this post or page. Simply add this embed code anywhere in your post content.

{{CODEmyjscode}}

You can now save your post or page and view your site. You will be able to see the javascript code by using the Inspect tool or by viewing the page source.

Tip: These methods are for beginners and website owners. If you are learning WordPress theme or plugin development, then you need to properly enqueue JavaScript and stylesheets to your projects.

We hope this article helped you learn how to easily add JavaScript in WordPress pages or posts. You may also want to see our list of extremely useful tricks for the WordPress functions file.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

210 Shares
Share
Tweet
Share
Pin
Popular on WPBeginner Right Now!
  • How to Start Your Own Podcast (Step by Step)

    How to Start Your Own Podcast (Step by Step)

  • Google Analytics in WordPress

    How to Install Google Analytics in WordPress for Beginners

  • How to Fix the Error Establishing a Database Connection in WordPress

    How to Fix the Error Establishing a Database Connection in WordPress

  • Checklist

    Checklist: 15 Things You MUST DO Before Changing WordPress Themes

About the Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. Trusted by over 1.3 million readers worldwide.

The Ultimate WordPress Toolkit

49 Comments

Leave a Reply
  1. Ashley says:
    Jan 10, 2021 at 10:49 pm

    This site is AMAZING!!! This is the third post in a row where I’ve hit the jackpot getting what I needed and did it in the easiest way possible. Thank you!!

    Reply
    • WPBeginner Support says:
      Jan 11, 2021 at 1:06 pm

      Glad our guides were helpful :)

      Reply
  2. Dude says:
    Dec 19, 2020 at 2:10 pm

    Hey, great stuff WPbeginners! The second method worked like a charm. I did have a question though. If I wanted to add another js code for another purpose, how should the code start. Because anything I add after the code is greyed out. I’m at a loss here. I want it to do the same but for another page. Any ideas will be appreciated.

    Reply
    • WPBeginner Support says:
      Dec 21, 2020 at 10:57 am

      It would heavily depend on the code you are using but you would want to ensure the code is before the /script tag

      Reply
  3. Jonathan says:
    Dec 13, 2020 at 6:09 pm

    Thanks. This article was exceedingly helpful. I went with the functions.php option. Worked well.

    Reply
    • WPBeginner Support says:
      Dec 14, 2020 at 11:53 am

      Glad our guide was helpful :)

      Reply
  4. Elise says:
    Dec 12, 2020 at 10:16 pm

    That worked. Thank you so much!

    Reply
    • WPBeginner Support says:
      Dec 14, 2020 at 11:33 am

      You’re welcome :)

      Reply
  5. Martin says:
    Nov 21, 2020 at 7:11 am

    Question on Method 3:

    After inputting the value and clicking on the “add custom field”, how do I get the code to display on my website frontend?

    Should I insert “{{CODEmyjscode}}” using a shortcode widget or text editor on the page?

    Reply
    • WPBeginner Support says:
      Nov 23, 2020 at 2:03 pm

      for the moment you would want to use the text or code editor.

      Reply
  6. Bret Bernhoft says:
    Nov 15, 2020 at 9:36 pm

    When I first began working with WordPress, JavaScript seemed like an impossibility for me. But fast forward to today and I’m writing the language every day; often in association with WordPress.

    I wish it had been clearer to me how easy it would have been to write JavaScript, when I first began this journey. Thank you for the tools and tips. I’ll have to give this a try.

    Reply
    • WPBeginner Support says:
      Nov 17, 2020 at 11:48 am

      Glad we could share some easy methods for adding JavaScript to your site! :)

      Reply
  7. ibrahim says:
    Jul 16, 2020 at 7:03 am

    It worked and helped me a lot. Thank you!

    Reply
    • WPBeginner Support says:
      Jul 16, 2020 at 9:12 am

      You’re welcome :)

      Reply
  8. Kat says:
    Jul 1, 2020 at 10:24 am

    I tried adding custom JS in my post, but nothing happens. I followed your exact directions for Method 3, but when I go to preview the page it’s just blank space where the JS is supposed to be. Any idea why?

    Reply
    • WPBeginner Support says:
      Jul 2, 2020 at 8:45 am

      You would want to take a look at the plugin’s FAQ for the most common reasons for that issue and how to resolve it.

      Reply
  9. Samuel says:
    Apr 18, 2020 at 6:02 pm

    How does this work with the new WordPress block system?

    I’m trying to embed this in a page, but it just shows as {{code1}} on the preview

    Reply
    • WPBeginner Support says:
      Apr 21, 2020 at 1:07 pm

      It would depend on the method you are using on your site for the plugin, they have an update in their FAQ section for how to use it at the moment.

      Reply
  10. Akash says:
    Apr 7, 2020 at 9:32 am

    Thank for this information. Really amazing and helpful post.

    Reply
    • WPBeginner Support says:
      Apr 8, 2020 at 8:38 am

      You’re welcome, glad our article was helpful :)

      Reply
  11. Alex says:
    Feb 11, 2020 at 11:37 am

    Hey, great guide! The problem is I don’t have “Custom Fields” under screen options… Any idea why?

    Reply
    • WPBeginner Support says:
      Feb 12, 2020 at 8:28 am

      Is your site on WordPress.com?

      Reply
  12. James says:
    Dec 14, 2019 at 6:06 am

    Hi. I have employed a programmer to create a tool, which he did in Javascript. I have been using Weebly but Weebly has become unresponsive to requests for help, to which hundreds of blogs testify. So, I’m looking at alternatives to Weebly. Could WordPress handle a 2 MB javascript tool?

    Thanks,

    Reply
    • WPBeginner Support says:
      Dec 16, 2019 at 10:27 am

      Your hosting would determine if a tool like that could be used not the platform for your website and depending on how the tool was set up would determine if you can transfer the tool.

      Reply
  13. Matt says:
    Aug 20, 2019 at 7:19 pm

    What if I need to add the script just on a single page but in the head not the body? I am trying to add a google conversion pixel just to my form submit thank you page.

    Reply
    • WPBeginner Support says:
      Aug 21, 2019 at 9:42 am

      You would want to take a look at the section of the article called: Adding JavaScript to a Specific WordPress Post or Page Using Code :)

      Reply
  14. quy says:
    Aug 19, 2019 at 11:15 pm

    it works like magic. Thanks very much

    Reply
    • WPBeginner Support says:
      Aug 20, 2019 at 10:24 am

      You’re welcome, glad our article could help :)

      Reply
  15. Manjeet Chhillar says:
    Aug 13, 2019 at 8:58 am

    Thank you for this very helpful post.

    My query is: How can I implement “Method 2” on multiple posts. Do i need to add Post ID of every single post separated by comma?

    Reply
    • WPBeginner Support says:
      Aug 13, 2019 at 10:43 am

      yes, you would need to place the commas outside the single quotes and start a new set of quotes for this method

      Reply
  16. Deborah says:
    Jun 10, 2019 at 12:40 pm

    Thank you for sharing the three methods WordPress users can use to add JavaScript to posts or pages. From what I read on the Insert Headers and Footers plugin page in the repository, the plugin doesn’t use the enqueue method to add the scripts. Which is the recommended method to add scripts in WordPress.

    Did I misunderstand? Or is Insert Headers and Footers using enqueue to add scripts? If it’s not using enqueue, do you know when the plugin will be updated to use enqueue?

    Reply
    • WPBeginner Support says:
      Jun 11, 2019 at 10:01 am

      The plugin is not enqueueing scripts added to it at the moment as not everything added with our plugin may not want to be enqueued. If you would like to enqueue the added code you would want to use another method.

      Reply
  17. Dave G says:
    Jun 2, 2019 at 2:49 pm

    Nice, thanks for that. It so happen that the exact post ID I needed to run javascript on was number 16. “`if (is_single (’16’)) { “`

    Are you from the future?

    :)

    Reply
    • WPBeginner Support says:
      Jun 3, 2019 at 1:12 pm

      Not yet at least :)

      Reply
  18. Golu Arjun says:
    May 23, 2019 at 2:40 am

    Thank you for this post. It’s very helpful. It is possible to customize

    Reply
    • WPBeginner Support says:
      May 23, 2019 at 11:27 am

      You’re welcome :)

      Reply
  19. Thomas says:
    May 16, 2019 at 12:08 pm

    I need to add a script to all posts in my blog. I have the plugin to each individual post. Thing is, there are thousands of posts and we need to add the script to all of them. Any suggestions? Thank you in advance.

    Reply
    • WPBeginner Support says:
      May 17, 2019 at 10:53 am

      The Insert Headers and footers option will put a code on every post and page for you if they are using the same code.

      Reply
      • Thomas says:
        May 18, 2019 at 9:57 am

        Thank you for your quick reply.

        We only want the script to run on Posts. We do not want it to run on all pages.

        Reply
        • WPBeginner Support says:
          May 20, 2019 at 12:56 pm

          If you had a widget that is only added to posts you could try adding the code in a widget.

  20. Ann says:
    Mar 26, 2019 at 6:59 am

    I’ve tried using the Headers and Footers scripts and the jQuery just doesn’t seem to be working properly.

    Reply
    • WPBeginner Support says:
      Mar 26, 2019 at 11:59 am

      It would depend on the specific code you are adding to the site for the possible reasons it could not be working. You may want to ensure with who you took the code from that the code itself is working.

      Reply
  21. Andrew Golay says:
    Jan 28, 2019 at 9:44 pm

    Please fix your Headers / Footer plugin or change this article, thank you.

    Reply
    • WPBeginner Support says:
      Jan 29, 2019 at 11:03 am

      Our plugin is currently working from testing but we will certainly take another look at it.

      Reply
  22. lynn says:
    Jan 13, 2019 at 2:15 pm

    thank you!! This was very helpful .

    Reply
    • WPBeginner Support says:
      Jan 14, 2019 at 2:29 pm

      Glad it was helpful :)

      Reply
  23. Remco says:
    Dec 31, 2018 at 5:34 am

    Thank you for this great post!
    Is it possible to implement Structured Data on Woocommerce pages with this method (JSON-LD)?

    Reply
    • WPBeginner Support says:
      Dec 31, 2018 at 2:18 pm

      You likely could but if you have an SEO plugin you are currently using you would want to check with that plugin to see if the plugin does that already.

      Reply
  24. graham says:
    Oct 19, 2018 at 10:04 am

    A well-presented roundup of the better-known options for what is becoming a common need. However, many WordPress users are not (and do not want to be) programmers. For them, JavaScript in any form is too frightening; that’s why they use WordPress with its promise of “no programming required”.

    There’s another possibility; to use custom scripts instead of JavaScript, and embed them directly in the page. You can put them in any component, though I prefer .

    All you need then is something that can compile and run the script. It’s hard to find plugins that can do this; my own searches haven’t yet turned up any. However, as a JavaScript programmer myself, I was able to write one and put it in the library as EasyCoder. The scripts resemble English, have about the same complexity as SQL and can do most of the things commonly required to manage content and interactivity in a web page. EasyCoder is also fully pluggable so other programmers can add modules themselves.

    Reply

Leave a Reply Cancel reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Over 1,320,000+ Readers

Get fresh content from WPBeginner

Featured WordPress Plugin
OptinMonster
OptinMonster
Convert website visitors into email subscribers. Learn More »
How to Start a Blog How to Start a Blog
I need help with ...
Starting a
Blog
WordPress
Performance
WordPress
Security
WordPress
SEO
WordPress
Errors
Building an
Online Store
Useful WordPress Guides
    • 7 Best WordPress Backup Plugins Compared (Pros and Cons)
    • How to Fix the Error Establishing a Database Connection in WordPress
    • Why You Need a CDN for your WordPress Blog? [Infographic]
    • 30 Legit Ways to Make Money Online Blogging with WordPress
    • Self Hosted WordPress.org vs. Free WordPress.com [Infograph]
    • Free Recording: WordPress Workshop for Beginners
    • 24 Must Have WordPress Plugins for Business Websites
    • How to Properly Move Your Blog from WordPress.com to WordPress.org
    • 5 Best Contact Form Plugins for WordPress Compared
    • Which is the Best WordPress Popup Plugin? (Comparison)
    • Best WooCommerce Hosting in 2021 (Comparison)
    • How to Fix the Internal Server Error in WordPress
    • How to Install WordPress - Complete WordPress Installation Tutorial
    • Why You Should Start Building an Email List Right Away
    • How to Properly Move WordPress to a New Domain Without Losing SEO
    • How to Choose the Best WordPress Hosting for Your Website
    • How to Choose the Best Blogging Platform (Comparison)
    • WordPress Tutorials - 200+ Step by Step WordPress Tutorials
    • 5 Best WordPress Ecommerce Plugins Compared
    • 5 Best WordPress Membership Plugins (Compared)
    • 7 Best Email Marketing Services for Small Business (2021)
    • How to Choose the Best Domain Registrar (Compared)
    • The Truth About Shared WordPress Web Hosting
    • When Do You Really Need Managed WordPress Hosting?
    • 5 Best Drag and Drop WordPress Page Builders Compared
    • How to Switch from Blogger to WordPress without Losing Google Rankings
    • How to Properly Switch From Wix to WordPress (Step by Step)
    • How to Properly Move from Weebly to WordPress (Step by Step)
    • Do You Really Need a VPS? Best WordPress VPS Hosting Compared
    • How to Properly Move from Squarespace to WordPress
    • How to Register a Domain Name (+ tip to get it for FREE)
    • HostGator Review - An Honest Look at Speed & Uptime (2021)
    • SiteGround Reviews from 4464 Users & Our Experts (2021)
    • Bluehost Review from Real Users + Performance Stats (2021)
    • How Much Does It Really Cost to Build a WordPress Website?
    • How to Create an Email Newsletter the RIGHT WAY (Step by Step)
    • Free Business Name Generator (A.I Powered)
    • How to Create a Free Business Email Address in 5 Minutes (Step by Step)
    • How to Install Google Analytics in WordPress for Beginners
    • How to Move WordPress to a New Host or Server With No Downtime
    • Why is WordPress Free? What are the Costs? What is the Catch?
    • How to Make a Website in 2021 – Step by Step Guide
Deals & Coupons (view all)
SendinBlue Coupon Code
Sendinblue Coupon
Get Sendinblue, a powerful marketing automation toolkit for small businesses, for FREE.
InMotion Hosting
InMotion Hosting Coupon
Get an exclusive 50% off InMotion hosting plus a free domain.
Featured In
About WPBeginner®

WPBeginner is a free WordPress resource site for Beginners. WPBeginner was founded in July 2009 by Syed Balkhi. The main goal of this site is to provide quality tips, tricks, hacks, and other WordPress resources that allows WordPress beginners to improve their site(s).

Join our team: We are Hiring!

Site Links
  • About Us
  • Contact Us
  • FTC Disclosure
  • Privacy Policy
  • Terms of Service
  • Free Blog Setup
  • Free Business Tools
  • Growth Fund
Our Sites
  • OptinMonster
  • MonsterInsights
  • WPForms
  • SeedProd
  • Nameboy
  • RafflePress
  • Smash Balloon
  • AIOSEO

Copyright © 2009 - 2021 WPBeginner LLC. All Rights Reserved. WPBeginner® is a registered trademark.

Managed by Awesome Motive | WordPress hosting by SiteGround | WordPress Security by Sucuri.