Beginner's Guide for WordPress / Start your WordPress Blog in minutes

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

Do you want to add JavaScript in your WordPress pages or posts?

Sometimes you may need to add JavaScript code to your entire website or into specific pages and posts. By default, WordPress does not let you add code directly in your posts.

In this article, we’ll show you how to add JavaScript in WordPress pages or posts easily.

How to easily add JavaScript in WordPress pages or posts (3 methods)

What is JavaScript?

JavaScript is a programming language that runs on the user’s browser, not on your server. 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 calculators, or some other third-party service, then you will be often asked to copy and paste a JavaScript code snippet into your WordPress 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>

But, 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 to WordPress pages or posts without breaking your website. You can use the quick links below to jump straight to the method you want to use.

Method 1. Add JavaScript to Entire WordPress Site Using Insert Headers and Footers Plugin

Sometimes a plugin or tool will need you to copy and paste a JavaScript code snippet into your website to work correctly.

Usually, these scripts will go in the header or footer section of your WordPress blog, so the code is loaded on every page view.

For example, when you install Google Analytics, the code needs to run on every page of your website, so it can track your website visitors.

You can manually add the code to your header.php or footer.php files, but these changes will be overwritten when you update or change your theme.

That’s why we recommend using a WordPress plugin to add JavaScript to your entire WordPress site.

The best plugin for the job is the Insert Headers and Footers plugin.

The first thing you need to do is install and activate the plugin. For more details, see our step by step guide on how to install a WordPress plugin.

Upon activation, you need to go to Settings » Insert Headers and Footers.

Here you will see three boxes for the header, body, and footer sections.

Insert headers and footers add code

You can now paste the JavaScript you copied into one of these boxes and click on the ‘Save’ button.

The plugin will now automatically load the code you added on every page of your website.

Method 2. Adding JavaScript Code to WordPress Manually Using Code

With this method, you need to add code to your WordPress files. If you haven’t done this before, then check out our guide on how to copy and paste code in WordPress.

First, we’ll show you how to add code to your WordPress site’s header. You need to copy the following code and add it to your functions.php, in a site-specific plugin, or by using a code snippets 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 Using Code

If you only want to add JavaScript to a single WordPress post, then you will need to add conditional logic to the code.

Take a look at the following code snippet:


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

The code above will only run the JavaScript if the post ID matches ’5’. Make sure you replace the ’5’ with your own post ID.

To find the post ID open up the post where you want the JavaScript to run. Then, in the URL of the page, you’ll find the post ID.

Find WordPress post ID

Adding JavaScript to a Specific WordPress Page Using Code

If you only want to add JavaScript to a single WordPress page, then you will need to add conditional logic to the code, just like above.

Take a look at the following example:

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');

The code above will only run the JavaScript if the page ID is ’10’. Make sure you replace the ’10’ with your own page ID.

You can find the page ID using the same method as above. Simply open the page you want the JavaScript to run and note the page ID in the URL.

Adding JavaScript to a Specific WordPress Post or Page Using Code in the Footer

If you want the JavaScript to run in your site footer instead of the header, then you can add the following code snippet to your website.

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

This code snippet hooks into wp_footer instead of wp_head. You can also add conditional tags to add javaScript to specific posts and pages like the examples above.

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

Another way you can add JavaScript to individual posts and pages is by using a plugin. You can select where in the content you want to embed your JavaScript code.

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

Upon activation, you need to edit the post or page where you want to add JavaScript. Then, you need to enable custom fields which is hidden by default.

To view it, you need to click on the three-dot menu in the top-right corner of the screen and then select ‘Options’ from the menu.

Post editor options

This brings up a popup where you need to check the ‘Custom fields’ option under the ‘Advanced panels’ section.

Then, click the ‘Enable & Reload’ button to reload the post editor.

Enable display custom fields

After that, you’ll see the ‘Custom Fields’ meta box directly below the content editor.

Next, click 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 the ‘CODE’ prefix (for example, ‘CODEmyjscode’) and then paste your JavaScript code into the value field.

Then, click the ‘Add Custom Field’ button to save your custom field.

Adding a JavaScript code to a 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}}

Make sure you click ‘Update’ or ‘Publish’ to save the page or post and make your JavaScript code live.

Pro 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 guide on how to choose the best blogging platform and our expert picks of the best AI chatbot software for your website.

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.

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us.

The Ultimate WordPress Toolkit

Get FREE access to our toolkit – a collection of WordPress related products and resources that every professional should have!

Reader Interactions

53 CommentsLeave a Reply

    • It should be at the top of the edit page. if you are using the classic editor then it would be under Screen Options.

      Admin

  1. I’m not getting the Custom Fields option in the Screen Options tab. I’m using a self-hosted website and have installed and activated the Code Embed plugin

    • If you’re using the Block editor then the setting has moved under the preferences area.

      Admin

  2. 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!!

  3. 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.

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

      Admin

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

  5. 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?

  6. 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.

  7. 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?

    • 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.

      Admin

  8. 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

    • 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.

      Admin

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

  10. 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,

    • 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.

      Admin

  11. 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.

    • 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 :)

      Admin

  12. 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?

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

      Admin

  13. 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?

    • 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.

      Admin

  14. 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?

    :)

  15. 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.

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

      Admin

      • 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.

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

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

    • 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.

      Admin

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

      Admin

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

    • 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.

      Admin

  18. 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.

Leave A 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.