Short Answer
To add JavaScript to WordPress, create a snippet in the free WPCode plugin, paste your code, and choose where it runs: your whole site, one page or post, or a spot inside your content. For a one-off script on a single page, WordPress 7.0’s Custom HTML block also has its own JavaScript tab.
Key Takeaways
- Every step in the WPCode method works on the free version, including loading a script on just one page or post.
- If your code has a
<script src=...>line, like many setup codes from other tools, add it as an HTML Snippet instead of a JavaScript Snippet. - Your snippet lives in WPCode, not your theme, so updating or switching themes doesn’t remove it.
- Script not working? Check the Active toggle, your cache, and your page rule first.
JavaScript is a programming language that makes websites interactive.
It’s what allows a menu to open when you click it, a booking form to respond to your selections, or a notification to appear without reloading the page.
Many WordPress plugins and third-party services also use JavaScript to add features to your site.
They might give you a short piece of code to display a booking widget, track visitor activity, or add another feature to a page.
You can add JavaScript to WordPress using WPCode, or use the built-in Custom HTML block in WordPress 7.0 and later. The best approach depends on what you want to do.
In this guide, we’ll show you both methods and how to control which pages load your script.
Use the table of contents to navigate the article below.
- Where Should Your JavaScript Run?
- How to Add JavaScript to WordPress With WPCode
- Add Scripts From the Post Editor With Page Scripts (Paid Plans)
- How to Add JavaScript to WordPress Without a Plugin
- Troubleshooting: My JavaScript Isn't Working
- FAQs: Add JavaScript to WordPress
- Add JavaScript to WordPress Without Touching Your Theme
Where Should Your JavaScript Run?
Before you paste anything, decide where the script needs to run.
| Where it runs | A typical example | What to use |
|---|---|---|
| 1. Your whole site | A chat widget or an analytics tag | A WPCode snippet set to Site Wide Header or Footer (Step 3) |
| 2. One page or post | An “Open now” badge on your Visit page | A WPCode snippet with a free Page URL rule (Step 4) |
| 3. Inside a post’s content | A signup prompt after the second paragraph | A WPCode snippet set to Insert After Paragraph, or a shortcode (Bonus section) |
| 4. A one-off script, no plugin | A script for one page that you won’t reuse | The Custom HTML block’s JavaScript tab, on WordPress 7.0 and later (no-plugin section) |
Rows 2 and 4 both put a script on one page.
A snippet keeps it in one place with an on/off switch, while the block keeps a separate copy on each page. Our walkthrough follows row 2. Step 3 shows how to load a script across your whole site, and the bonus section covers placing one inside your content.
Already use WPCode’s Code Snippets » Header & Footer screen? Scripts there run on your whole site, like row 1. Our guide to adding header and footer code covers that screen.
How to Add JavaScript to WordPress With WPCode
For our example, we’ll add an “Open now” badge to the Visit Us page of our coffee shop test site.
The script checks the time in the shop’s time zone and shows Open now or Closed now under the opening hours, on that one page only.
The screenshot below shows you how the badge looked after setup.

And you can do all of it with the free version.
Step 1: Install WPCode (Free)
WPCode is a free WordPress snippet plugin that keeps your code outside your theme.
Each piece of code lives in its own snippet, with its own on/off switch.
To get started, install WPCode from the WordPress plugin directory and activate it.

If you need a hand, see our guide on how to install WPCode.
Once installed and activated, you’ll see a new Code Snippets menu in your dashboard.
Step 2: Create a JavaScript Snippet
Next, go to Code Snippets » + Add Snippet.
Hover over the Add Your Custom Code (New Snippet) card, then click the + Add Custom Snippet button that appears on it.

WPCode then asks which kind of code you’re adding. Choose JavaScript Snippet.
Check your code first, though.
If it has a line that starts with <script src= or <script async src=, choose HTML Snippet instead.
You may see this in setup code from another tool. Code like that doesn’t hold the JavaScript itself. It links to a file on the tool’s servers, and the browser needs the whole <script src=...> tag to fetch it.
A JavaScript Snippet removes that opening tag when you save, so an HTML Snippet is the right type. If you choose an HTML Snippet, the remaining steps are the same.

Now give your snippet a name you’ll recognize later. We called ours “Harbor & Pine: Open Now Badge”.
Then paste your code into the Code Preview box, the editing area. Make sure the Code Type, in the top right, reads JavaScript Snippet.
With the code pasted in, your editor should look like the screenshot below:

Here’s the full code from our example, if you want to try it. Change the hours and the time zone to match your business. Time zones use standard names, like America/Chicago or Europe/London.
Our example assumes the shop opens every day. If your business has closed days, the hours list and the “We open tomorrow” line will need adjusting.
// Show "Open now" or "Closed now" under the opening hours
document.addEventListener('DOMContentLoaded', function () {
// Opening hours as [open, close] on a 24-hour clock. 0 = Sunday.
var hours = {
0: [8, 16], 1: [7, 16], 2: [7, 16], 3: [7, 16],
4: [7, 16], 5: [7, 16], 6: [8, 16]
};
// Read the day and hour in the shop's time zone, not the visitor's
var parts = new Intl.DateTimeFormat('en-US', {
timeZone: 'America/New_York', weekday: 'short', hour: 'numeric', hourCycle: 'h23'
}).formatToParts(new Date());
var part = function (type) {
return parts.filter(function (p) { return p.type === type; })[0].value;
};
var day = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(part('weekday'));
var hour = parseInt(part('hour'), 10);
var today = hours[day];
var isOpen = hour >= today[0] && hour < today[1];
var opensLaterToday = hour < today[0];
var nextOpen = opensLaterToday ? today[0] : hours[(day + 1) % 7][0];
var label = function (h) { return (h % 12 || 12) + (h < 12 ? 'am' : 'pm'); };
var badge = document.createElement('p');
badge.textContent = isOpen
? 'Open now, until ' + label(today[1])
: 'Closed now. We open ' + (opensLaterToday ? 'at ' : 'tomorrow at ') + label(nextOpen) + '.';
badge.style.display = 'inline-block';
badge.style.padding = '6px 14px';
badge.style.borderRadius = '999px';
badge.style.fontWeight = '700';
badge.style.color = '#fff';
badge.style.background = isOpen ? '#2E7D4F' : '#9A3B2E';
// Place it right under the "Opening hours" heading
var heading = document.getElementById('hours');
if (heading) {
heading.insertAdjacentElement('afterend', badge);
}
});
Check out our guide on copying and pasting code snippets for tips on pasting cleanly.
The last part of the code puts the badge under a heading with the ID hours.
To give your own heading that ID, open your page in the block editor and click the heading. In the block settings sidebar, open Advanced and type hours in the HTML anchor field. Then save the page.
Should you paste the <script> tags too? For code that sits between the tags, like ours, either works.
WPCode wraps your code in <script> tags when it runs. That’s the grey <script> line above line 1 in the screenshot. If you paste one pair of tags around your code, WPCode removes it when you save.
⚠️ Already made a JavaScript Snippet for code with a <script src=...> line?
Switch the Code Type dropdown in the top right to HTML Snippet. Then delete the code, paste it again exactly as the tool gave it, and click Update. A JavaScript Snippet removed that first line when you saved, so the file never loads.
Only paste code from a tool or person you trust. It runs on your site as-is, and WPCode doesn’t catch mistakes inside JavaScript.
Step 3: Choose Where the Script Loads
Now scroll down to the Insertion box and leave Insert Method on Auto Insert.
Then open the Location dropdown.
By default, a new WPCode snippet starts on Site Wide Header. That loads the code near the top of every page, before the page content.
But for scripts like this, Site Wide Footer is the better pick. It loads after the page content, so the headings, buttons, and forms your script works with are already there.
Pick Header only when the tool’s instructions ask for it.
For our demonstration, we picked Site Wide Footer:

If you stop here, the script runs on every page of your site. That’s right for a chat widget or a site-wide tracking tag, like Google Analytics.
Our badge only belongs on the Visit Us page, so the next step limits it.
Step 4: Load JavaScript on One Page or Post (Free)
To do this, scroll down to the Smart Conditional Logic box and switch on Enable Logic.
Next, build the rule. Choose Show, then Page URL, then Contains.
In the last box, type the part of your page’s address that comes after your domain. You can copy it from your browser’s address bar while you view the page. Keep the slashes at both ends, like ours: /harbor-pine/visit/.
Our finished rule looks like this:

Use the full URL path for that page, since Contains matches any address with that text in it. If you use a single word or a phrase, the script may run on a similar page too.
The same rule works for a post. Open the post, copy the part of its address after your domain, and paste it in.
For your home page, use a different rule. Its address is just a slash (/), and every address contains that. Choose Type of page instead, and set it to Homepage. It’s free on WPCode too.
Need the script on more pages? Click + Add new group and add another Page URL rule. The snippet then runs when either rule matches.
Our guide to adding scripts to specific pages covers more rules available on the free version of WPCode, like post type and user role.
Picking the page by its title, instead of its address, is the Post/Page rule. That one comes with the paid plans.
Step 5: Turn On the Snippet and Check the Page
Scroll back to the top and flip the toggle from Inactive to Active. Then click Save Snippet.
On a snippet you’ve saved before, this button reads Update.
If your site uses a caching plugin, clear its cache now. Not sure? Here’s how to tell if a page is cached.
Then open your page in a private window, so you see it the way a visitor does.
On our site, the badge sits right under Opening hours. We checked before the shop opened, so it reads Closed now. We open at 7am.
Here’s the result on the Visit Us page.

Then open any other page on your site. The badge shouldn’t be there.
If the badge looks wrong, or something else on the page stops working, flip the toggle back to Inactive and click Update. Your code stays saved for when you’ve fixed it.
Bonus: Place Your Script Inside a Post (Free)
Our badge doesn’t need this since its script finds its own place on the page.
But you might want something like a signup prompt to show up after the second paragraph of your post. In this case, you need to add code inside your content.
You have two ways to place it.
Option 1: After a paragraph
In the same snippet editor you used above, open the Location dropdown and click the Page-Specific tab. Pick Insert After Paragraph.

A box labelled after paragraph number appears. Type 2 to place the code after the second paragraph, or another number to place it under that paragraph.

This location works on every post and page by default. So keep your Page URL rule from Step 4 turned on so it only appears where you want.
Click Update, then check the page again.
Option 2: In one exact spot
Switch Insert Method to Shortcode and click Update. Copy the shortcode from the Insertion box.

Paste it into a Shortcode block where the code should appear.
You don’t need a Page URL rule here. The code only runs where you paste the shortcode.
⚠️ Tip
If your tool gives you HTML along with the script, like a form with a <div>, use an HTML Snippet in Step 2 instead. Our custom HTML guide walks through it.
If you add scripts to single posts often, the paid plans have two shortcuts for that.
Add Scripts From the Post Editor With Page Scripts (Paid Plans)
All paid plans let you skip typing page addresses.
The first is the Post/Page rule in Smart Conditional Logic. It lets you pick pages and posts by their titles instead of their addresses.
The second is the WPCode Page Scripts box. It appears under the block editor when you edit a post or page.
The box has Header, Footer, and Body tabs. Paste a script into one, update the post, and it loads on that post only.
The screenshot below shows the box on our Visit Us page, with the Footer tab open:

Each tab also has a checkbox, like Disable global Footer scripts on this page.
It only affects WPCode’s Code Snippets » Header & Footer screen, which has one big box each for header, body, and footer code. Ticking it switches off that screen’s footer code on this page. The Header and Body tabs each have their own checkbox.
Snippets you build with the steps above aren’t affected. To keep a snippet off a page, use a Page URL rule.
The box is handy for a one-off script on one post. For code you’ll reuse, a snippet is still the better home.
Paid plans also let you schedule snippets, show them only on desktop or mobile, and track every change with code revisions. You can compare the plans on the WPCode pricing page.
How to Add JavaScript to WordPress Without a Plugin
If a script only goes on one page, you can also add it without a plugin.
Since WordPress 7.0, the Custom HTML block has its own code window with HTML, CSS and JavaScript tabs.
To use it, add a Custom HTML block to your page and click the Edit HTML button in the middle of the block (on a block that already has code, it reads Edit code).
Next, open the JavaScript tab and paste your code.
Got a setup code with a <script src=...> line? Paste it in the HTML tab instead, exactly as the tool gave it.
Click Update at the bottom of the code window to close it, then save the page.

The tabs only show for users who are allowed to post unfiltered HTML. On a regular site, that’s Administrators and Editors by default.
Authors and Contributors don’t see them, and WordPress removes any script they paste.
On a multisite network, only Super Admins can add scripts this way.
Still on WordPress 6.x? The block has no tabs. You paste the whole script into the block, <script> tags included.
This works well for one script on one page. Each page keeps its own copy of the script, so changing it later means finding and editing every page that has it. And WordPress has no list of which pages those are.
Our guide to adding custom HTML to WordPress covers this block in detail.
You’ll also find tutorials that add JavaScript through your theme’s functions.php file. That’s a developer route. A typo there can break your site, and a theme update can wipe the change out.
If you do go that way, follow our guide to adding code to functions.php safely.
Troubleshooting: My JavaScript Isn’t Working
Start with the problem that matches what you’re seeing.
“I added it, but nothing happens.”
First, check the toggle at the top of your snippet. It needs to read Active.
Next, clear your cache. Caching plugins and many hosts save a copy of each page, and visitors keep seeing the old copy until it refreshes.
Then check your rule. Compare the page’s address with the text in your Page URL rule. One typo or extra character is enough to stop a match.
Still nothing? Your script may run before the part of the page it changes has loaded.
If the snippet is on Site Wide Header, switch it to Site Wide Footer, so the script loads after the page content. If your code came from a developer or an AI chat, ask them to wrap it in a DOMContentLoaded listener, like our example.
“It shows up on pages it shouldn’t.”
A Site Wide location runs on every page, and Insert After Paragraph on every post and page, until you add a rule.
Go back to Step 4 and add a Page URL rule. Then check that Enable Logic is switched on, because the rule doesn’t apply while it’s off.
“It works on some pages but not others.”
Open a page where it fails, and compare its address with your Page URL rule. The rule may only match some of the pages you meant.
Next, check that the page has what the script looks for. Our badge needs a heading with the ID hours. On a page without one, it does nothing.
Then check your speed plugin. Some caching and optimization plugins delay or combine scripts, and that can stop a script from running. Try leaving your script out of those features. Here’s how to exclude a script from minification in WP Rocket, for example.
“My tool’s code doesn’t load.”
Look at the first line of the code the tool gave you.
If it starts with <script src= or <script async src=, it loads a file from the tool’s servers.
A JavaScript Snippet removes that opening <script src=...> tag when you save, so the file never loads. Open the snippet, switch Code Type to HTML Snippet, and paste the code again exactly as the tool gave it. Then click Update.
💡 Got an AI assistant connected to your site?
Turn on WPCode’s AI & Automation Access, and your assistant can read your snippet’s code, fix it, and update the snippet for you. The setting is free in WPCode Lite and needs WordPress 6.9 or later.
Copy the red error from your browser’s Console into the chat, so it knows what went wrong. The FAQ below shows where to find it.
WPCode’s automatic code check only covers PHP snippets. So open your page again after the fix and make sure the script works.
FAQs: Add JavaScript to WordPress
Should JavaScript go in the header or the footer?
Use the footer unless the tool’s instructions say header. Footer scripts load after the page content, so they’re less likely to hold up what visitors see first. Analytics and site verification tags often ask for the header, so they can load early.
Will adding JavaScript slow down my site?
A small script like our badge won’t make a noticeable difference. Large third-party scripts can.
In one of our speed tests, a Google Maps embed loaded on every page added over 300 KB of scripts to pages with no map.
Limiting it to the Contact page took it off the rest. On the free version, a Page URL rule does that job.
How do I know if my JavaScript has an error?
Open the page, right-click anywhere, and choose Inspect. Then open the Console tab. Look for a red error that mentions your script or a line from it. If you find one, check the code with whoever gave it to you.
Can Editors add JavaScript too?
In the Custom HTML block, yes. Editors and Administrators can use its JavaScript tab. WPCode is different: only Administrators can use it by default. An Administrator can give other roles access under Code Snippets » Settings » Access Control, which comes with WPCode Pro and up.
Add JavaScript to WordPress Without Touching Your Theme
You now know how to add JavaScript to WordPress and choose exactly where it runs.
Start with one script you already have. Find its row in the table above, and set it up to load only where it’s needed.
Looking for something to try next? Our list of JavaScript snippets for WordPress has 13 copy-and-paste scripts, like click-to-call links and a reading progress bar.
If you’re adding JavaScript to more than one page, or you expect to change it later, keep it in one place. WPCode lets you do that without editing your theme files.
Want to manage every script from one place, with an on/off switch for each?
Get WPCode for free →
Want to add scripts right from the post editor and pick pages by name?
See WPCode pricing →
Additional Resources
These guides help you do more with code on your site.
- How to Add PHP to WordPress Posts and Pages: run PHP in a post the same safe way.
- How to Add Custom CSS to Your WordPress Site: change how your site looks without editing theme files.
- 9 Tips to Easily Manage Code Snippets in WordPress: keep your snippets tidy as the list grows.

