Loading WordPress’ Thickbox Only When Needed

I like to use Thickbox on my site to display images and videos in overlay windows. In WordPress, it’s easy enough to use wp_enqueue_script( ) and wp_enqueue_style() to load the built-in version of Thickbox. It automatically takes care of including jQuery, putting the css in the header, and the javascript in the footer.

But there’s no need to have the bloat of Thickbox and jQuery loading on all pages when most of them don’t even use it. That’s why Joost de Valk detailed a nice tip to only load thickbox when needed by checking the page content for references to it. All it takes is a few lines of code in your functions.php file.

Unfortunately, you end up with some broken images because the built-in Thickbox defines their locations in thickbox.js as relative paths:


var tb_pathToImage = "../wp-includes/js/thickbox/loadingAnimation.gif";
var tb_closeImage = "../wp-includes/js/thickbox/tb-close.png";

Those paths get tacked onto the URL of whatever page you’re on, which results in an invalid URL and a couple 404 errors for each use. Now that’s not unique to Joost’s solution. It happens whenever Thickbox is loaded with wp_enqueue_script( ).

It can easily be fixed by adding a couple lines of javascript in the footer to redefine the image path variables. That’s as simple as a few more lines of code in your functions.php file. We’ll use Joost’s technique of only loading it when the page content requires it:


function thickbox_image_paths() {
	global $post;
	wp_reset_query();
	if (is_singular() && strpos($post->post_content,'class="thickbox"') !== false) {
		$thickbox_path = get_option('siteurl') . '/wp-includes/js/thickbox/';
		echo "<script type=\"text/javascript\">\n";
		echo "	var tb_pathToImage = \"${thickbox_path}loadingAnimation.gif\";\n";
		echo "	var tb_closeImage = \"${thickbox_path}tb-close.png\";\n";
		echo "</script>\n";
	}
}
add_action('wp_footer', 'thickbox_image_paths');

My theme uses multiple loops so I had to add the wp_reset_query() to be able to examine the original content. Otherwise it would be looking at the last post in my recent posts box and not see that Thickbox was used in the current content.

There you have it. A nice technique from Joost and a simple addition to complement it.

2 thoughts on “Loading WordPress’ Thickbox Only When Needed”

  1. Is this compatible with WordPress 3.0+ ?

    I’ve not been able to get it, nor Yoast’s working. I did have some success with _mfileds’ variation [http://wordpress.mfields.org/2010/thickbox-for-wordpress-gallery/]. That loaded thickbox background and box, but sans everything else.

Leave a Reply