Add JavaScript to One Page Only in WordPress

This is my solution to loading JavaScript on one page only — for example, a form that requires some validation code. In this case, I’m testing for the existence of a shortcode used to insert my form on the page, but other conditional tests are possible (my RSVPMaker event scheduling plugin tests for $posts->post_type == 'event').

The official documentation on the right way to load JavaScript says something about using the ‘init’ action to trigger a wp_enqueue_script function call. The enqueue function prevents multiple copies of the same script from being loaded and also allows you to specify dependencies. However, with ‘init’ you tend to wind out with the script being output on every page whether it’s needed or not. The ‘wp’ action loads just enough later that it’s possible to access the global $post for a WordPress page or single post view, but it still comes before WordPress outputs the page header and scripts.

Then you can do this:

<?php
function load_my_js() {

if(is_admin() )	return; // never mind if this is an admin page

global $post;
if(strpos($post->post_content,'[demoform]') == false)	return;

wp_register_script( 'js_test', plugins_url() . '/demo/test.js', array('jquery') );

wp_enqueue_script('js_test');

}

add_action('wp','load_my_js');
?>

This is loosely based on a post about conditionally loading JavaScript and CSS by Artem Russakovskii. He has a somewhat more complicated function that loops through multiple posts, but I think mine is a little simpler for something like a contact form intended to be used on a separate page.

Is there a reason why this wouldn’t work?

Be Sociable, Share!

  • Denis

    Hi, for me this doesn't work. I'm try to include prettyPhoto.js only on page which contain rel=”prettyPhoto”. With your code js doesnt load for all pages. I'm change “==false” to “!==false” and js displays on all pages. How to make it work I don't know, please help me. Thanks.

  • http://philipwalton.com Philip

    This plugin will do exactly what you want:
    http://philipwalton.com/2011/09/25/per-post-scripts-and-styles/

    I was having a similar issue the other day, and all the existing plugins sucked, so I wrote my own. I hope this helps someone!