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

wordpress_javascript

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

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