JavaScript in WordPress

39. JavaScript in WordPress.

JavaScript does work in WordPress. It can be used in WordPress template files in WordPress Themes or Child Themes. JavaScript can’t be added to post content without a special WordPress Plugin which removes the filters that prevent unwanted code within the post content area, for the protection of the user.

The safe and recommended method to add JavaScript to a WordPress page, and WordPress Theme or Plugin, is to use wp_enqueue_script(). This function includes the script if it hasn’t already been included, and safely handles assurance.

To use JavaScript repeatedly in your site, you may either set the call for the JavaScript, or the script itself, in the head of your header.php template file, between the meta tags and the style sheet link, the same way as you would if you were using JavaScript in any HTML page.

To “load” the JavaScript file into your site, in the head, add something like this:

<script type=”text/javascript” src=”/scripts/emailpage.js”></script>

If your custom JavaScript doesn’t work after including the previous line of code in your header.php template file, you should use the following line of code.

<script type=”text/javascript” src=”<?php bloginfo(‘template_url’); ?>/pathto/yourscript.js”></script>

You should include the leading forward slash “/”, even if your file is located in the root of your theme.

Make sure that you define the type correctly, as your site will not validate without it.

In the spot where you want to use the JavaScript, you must set the call for the JavaScript. For instance, you are using a JavaScript that sets a link for users to “email this page” to a friend, and you want it to be under the post title.

It may look like this:

<h3 class=”storytitle”>

 <a href=”<?php the_permalink() ?>” rel=”bookmark”>

 <?php the_title(); ?></a>


<div class=”emailpage”>

 <script type=”text/javascript”><!–//–><![CDATA[//><!–




If you want to use JavaScript inside of posts in WordPress, you should  take a few more steps, you need to combine the call to the script file with the call to the JavaScript itself.

<script type=”text/javascript” src=”/scripts/updatepage.js”></script>

<script type=”text/javascript”>




If your JavaScript does not work, triple check that you have not made any errors during the cut and paste into a group or single file. Be sure you used a text editor, and not a word processing program, to create the JavaScript file. Check the name of the function in the script file, as well as on your site. Not all JavaScript may work, and could possibly conflict with your PHP commands, but this is very rare.

Hope you liked this article, guys!

Share this!

Leave a Comment

Your email address will not be published. Required fields are marked *