How to add JavaScript to WordPress posts or pages ?

All WordPress posts and pages that are written using the built in WYSIWYG editor do not support JavaScript. If you are like me and want to add JavaScript to WordPress posts or pages without any plugins then there are a few points that you need to remember.

add JavaScript to WordPress posts

Do not use visual editor to add JavaScript to WordPress posts

Visual WYSIWYG editor should not be used . By default you get access to the “Visual” tab of the editor. This editor can modify all your XML/HTML tags that you have used and therefore you can lose any scripting logic. The editor will convert “<” or “>” to “&lt;” or “&gt;”.

Write HTML code to add JavaScript to WordPress posts

Switch to “HTML” tab of your editor for writing any JavaScript. This will preserve any HTML/XML tags that you use. Any changes made on this tab will be treated as HTML code rather than plain text.

Avoid new lines where you intend to add JavaScript to WordPress posts

Even when using HTML tab of your editor, WordPress might still create <p> and </p> tags around the JavaScript and make it unusable. There is however a way to get around that. First thing that you need to do is avoid any new lines before <script> tag, after </script> tag and hopefully in between. If there is any new line then WordPress will generate paragraph (<p>) tags for it. You can definitely check if paragraph tags are being inserted by viewing the source of the post with JavaScript on it.

Add JavaScript to WordPress posts along with PHP

If you are writing PHP code and calling it from the WordPress post or pages (this can be done by using appropriate WordPress plugins) then again you need to make sure that there are no new lines around the script tags. One technique I use is, I remove all new lines first and then echo the HTML code. Here is an example :

 <? require_once('myfile/that/contains/javascript/and/php/code)?> <? echo str_replace("\n","",get_my_javascript_html_code()); ?>

Alternatively you can also put in <div> tags around your JavaScript and this would avoid any <p> tag insertion.

Using plugins to add JavaScript to WordPress posts or pages

Finally if this is not your cup of tea then you can try some WordPress plugins. I could not find any good ones that automatically allow JavaScript based on regular <script> tags but it could be worth checking time to time for new ones.

Related Posts