Loading Javascript Only When Specific Content Existing in a Post?

Not sure what exactly your code is doing wrong but here’s code that does it right. I’ve decided to wrap the code in a class to be used for your plugin, and for humor I called it “Ugly Photo Plugin.” Here’s the full code:

<?php
/*
Plugin Name: Ugly Photo Plugin
*/
class UglyPhotoPlugin {
  static function on_load() {
    add_action('wp',array(__CLASS__,'wp'));
    add_shortcode('ugly-photo',array(__CLASS__,'ugly_photo_shortcode'));
  }
  static function ugly_photo_shortcode($attributes,$content,$code) {
    return '<div rel="ugly-photo">' . $content . '</div>';
  }
  static function wp() {
    if (!is_admin()) {
      global $post;
      if (strpos($post->post_content,'[ugly-photo]') !== false) {
        wp_enqueue_script( 'jquery' );
        wp_enqueue_script( 'js_test', 
          plugins_url('/demo/test.js',__FILE__), 
          array('jquery') );
      }
    }
  }
}
UglyPhotoPlugin::on_load();

Note that I’ve decided to use a shortcode [ugly-photo] and am testing for it instead of 'rel="prettyPhoto"' because WordPress’ WYSIWYG TinyMCE editor will strip out the "rel" value from your <div> so using the shortcode solves that problem.

Here’s what the post looks like when editing:

WordPress Post Editor with 'Ugly Photo' Shortcode
(source: mikeschinkel.com)

Here’s what my Javascript File has in it and where I’ve located it:

https://mikeschinkel.com/websnaps/skitched-20101225-004514.jpg
(source: mikeschinkel.com)

And finally here is the result:

Conditional Loading of Javascript in WordPress
(source: mikeschinkel.com)

P.S. Happy Holidays!

Leave a Comment