Adding javascript functionality to WordPress posts

Adding your own javascript implementation to posts in your wordpress blog is slightly more difficult then one might think. The difficulties stem from two things.

  • WordPress editors format html and javascript in posts.
  • The process to use a javascript file in a post is not straightforward.

Avoiding automatic formatting

There are probably several ways to accomplish this, but if found that a plugin called Text Control gives you lots of options as to how your posts are formatted, allowing javascript to be written in posts without a lot of difficulty.

Using javascript in a post

Since I want to use plots often, I choose to add the javascript files to the theme header.php file. The files can be included before the title tag in the header.php. The php command to include javascript files are as follows:

<?php
   wp_enqueue_script('data',plugins_url('/pathtojs/plots.js'));
?> 

This registers the javascript file with WordPress so that it knows where to look when a file referenced in a post. You need to include every javascript file you are using, not just the one you will be using in an eventual post.

Inside posts you only need to add files which contain methods that you use. These files are declared like this:

<script type="text/javascript" src="/pathtoplot/plots.js">
// <![CDATA[// ]]></script>

The javascript code using the declared files go in similar tags:

<script type="text/javascript">// <![CDATA[
//lots of great javascript stuff calling plots.js
// ]]></script>

An example of this in action can be seen in my previous blogpost concerning javascript scatterplots.

Published by

admin

Computer graphics/Visualization enthusiast

Leave a Reply

Your email address will not be published.