Thickboxing in WordPress themes

The lovely Thickbox jQuery plugin appears to no longer be supported by it’s creator, Cody Lindley, but it’s included with WordPress (it provides the “popup” overlays in the post editor for uploading and inserting images and other media), very flexible and that’s good enough reason for me to use it for the time being.

I’ve always been a bit shy of using Thickbox in the front end of WP sites, as the close button and loading animation paths are hard-coded relative to the WP admin area… in short, they don’t work at the front without tinkering. Today I realised that the required tinkering was (relatively) trivial, so here’s my code for including thickbox at the front end, you can drop it into the functions.php of your theme or make it into a plugin.

function my_load_thickbox() {
	add_thickbox();
	?>
	<script type="text/javascript">
		/* <![CDATA[ */
		var tb_pathToImage = '<?php echo esc_js( includes_url( '/js/thickbox/loadingAnimation.gif' ) ); ?>';
		var tb_closeImage = '<?php echo esc_js( includes_url( '/js/thickbox/tb-close.png' ) ); ?>'; 
		/* ]]> */
	</script>
	<?php
}
add_action( 'wp_head', 'my_load_thickbox', 0 );

Taking this section by section:

The add_thickbox function is a wrapper for adding the styling and script for Thickbox; the style gets added to the HTML HEAD element, and the script is added to the footer.

The script block is where the Thickbox image paths are corrected, the technique works because the WP Thickbox script checks if these two paths are set a JS vars before it sets them and uses any pre-existing values. Because the vars in the function above are set before the Thickbox script is loaded (the script has been added to the footer, remember) we are able to override and set some paths which will work on the front end of a WP site. The include_urls function is a handy way to reference some code inside the wp_includes directory (which the two Thickbox images are). The esc_js escapes text for a JS context, it’s included to prevent something hairy and completely unexpected getting into the JS and making a security mess everywhere (it’s always a good idea to escape anywhere and everywhere you can).

(One gotcha: because the scripts are added to the footer, your theme must include a wp_footer action.)

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.