How to Add JavaScript to your WordPress Posts

by Preetha 2012-09-10 17:12:42

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.

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.



Tagged in:


You must LOGIN to add comments