How to Add JavaScript to your WordPress Posts

.While you can easily add JavaScript code to your WordPress site by modifying the theme files, there can be instances when you may want to insert JavaScript inside specific posts or pages and not the entire site. How do you do that?

If you are running the self-hosted version of WordPress (not, you can sometimes add JavaScript through the built-in editor itself. Just change the writing mode from Visual to HTML and copy-paste your JavaScript code into the text box.


Adding JavaScript to WordPress – An Alternative

However, if the above option doesn’t work with your JavaScript, here’s an even better option that makes use of custom fields and short-codes. I also prefer this method for inserting JavaScript and you can see it in action in my one my previous posts.

The idea is that instead of adding the JavaScript code directly inside your post, you create a new custom field and set the value of this custom field to the JavaScript code. Then insert a shortcode in your post content which will in turn fetch the value of that custom field.

There are quite a few WordPress plugins that let you display custom field values via shortcodes though I use the one by @gonahkar. So here’s the full workflow again:

  1. Add a new Custom Field (say js) and paste the JavaScript widget into the Value field.

  2. Switch to the HTML mode in your WordPress editor and insert [cf]CUSTOM_FIELD_NAME[/cf] in a new line. Save, publish and WordPress will substitute that shortcode with the actual JavaScript code. That’s it.

WordPress Custom Fields

Shortcode for JavaScript Include JavaScript in your WordPress post with Shortcode and Custom Fields

Also see: Recommended WordPress Plugins

Amit Agarwal

Amit Agarwal

Google Developer Expert, Google Cloud Champion

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.

Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory


Awards & Titles

Digital Inspiration has won several awards since it's launch in 2004.

Google Developer Expert

Google Developer Expert

Google awarded us the Google Developer Expert award recogizing our work in Google Workspace.

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards in 2017.

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional (MVP) title for 5 years in a row.

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator title recognizing our technical skill and expertise.

Email Newsletter

Sign up for our email newsletter to stay up to date.

We will never send any spam emails. Promise.