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 WordPress.com), 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:
Add a new Custom Field (say
js
) and paste the JavaScript widget into the Value field.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.
Include JavaScript in your WordPress post with Shortcode and Custom Fields
Also see: Recommended WordPress Plugins
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