Howto Add JavaScript to Single WordPress Posts

One of our blog readers asked me the following question so I thought I’d do a quick post on it. It could be very useful if your trying to do demo pages on your blog which need JavaScript or jQuery to run.

“How can I run a JavaScript within a single WordPress blog post?”


Problem

They had previously been including a .js script file in every page on their site in the WordPress header.php. This is not ideal as all the JavaScript within would load for every page on the site. Unnecessary overhead!

<script type="text/javascript" src="http://www.domain.com/scripts/javascript.js"></script>

If you hadn’t noticed when you add JavaScript directly into the HTML editor in WordPress and reload the page is adds

tags to the JavaScript code. Hence, breaking the javascript.

wordpress-putting-code-in-paragraphs2

Best Solution

Create a custom field which can be included in the header and specified for each individual post. This means only the post which needs the JavaScript will actually load it! The custom field section should appear at the bottom of each post in the editor just below trackbacks.

Create a custom field called say “single-post-js” and past the javascript code into there.

wordpress-putting-code-in-custom-field

Then add the following code into header.php to pickup the custom field if it was a single post and the custom field was present.

<!-- single post js -->
<?php
  if( is_single() and $singlePostJs = get_post_meta($post->ID, 'single-post-js', true) )
   echo $singlePostJs;
?>

That’s it! It’s working!

wordpress-putting-code-working

Demo

The following jQuery code has been included for this post only. The reason for including the script tags inside the custom field and not in the PHP is that I can also use this field for CSS, but should probably create another custom field to manage that. Your choice.

inpost-code-demo
Run

Just do a quick check on other posts and pages without the custom field and check they are not affected by the new field. Hope this helped you!