Thickbox for WordPress Gallery

Posted on

By Michael Fields

I’m working on a theme project this morning and I needed to enable thickbox on the front-end of the site for a few different image galleries created with the gallery shortcode. Here is the solution that I came up with. I believe it to be the easiest way to accomplish this task with the smallest footprint on a WordPress installation. Please let me know your thoughts in the comments section.

wp_enqueue_script( 'thickbox' );
wp_enqueue_style( 'thickbox' );
add_action( 'wp_print_footer_scripts', 'enable_thickbox_for_gallery_shortcode' );
function enable_thickbox_for_gallery_shortcode() {
print <<<EOF
<script type="text/javascript">
/* <![CDATA[ */
jQuery( document ).ready( function( $ ) {
	tb_init( '.gallery-icon a' );
/* ]]> */

Previous + Next

The above solution works well to activate the default functionality of Thickbox. If you would like to take it a step further and activate the previous + next navigation within Thickbox, your links will need a rel attribute defined. The following code seems to work well for this.

add_filter( 'wp_get_attachment_link', 'add_rel_attribute_to_attachment_link', 1, 2 );
function add_rel_attribute_to_attachment_link( $anchor_tag, $image_id ) {
	$image = get_post( $image_id );
	$rel = '';
	if( isset( $image->post_parent ) ) {
		$rel = ' rel="attached-to-' . (int) $image->post_parent . '"';
	if( !empty( $rel ) ) {
		$anchor_tag = str_replace( '<a', '<a' . $rel, $anchor_tag );
	return $anchor_tag;

2 Comments Comments are closed

  1. Steve August 8, 2010 at 6:14 pm

    Nice, I’m not great at code, does `tb_init( ‘.gallery-icon a’ );
    ` mean this will load thickbox script/css only on posts with a gallery?

  2. Michael Fields August 8, 2010 at 6:42 pm

    Hi Steve. Nope. All tb_init( ‘.gallery-icon a’ ); does is tell the thickbox script to open a new thickbox when any link inside an element with the “gallery-icon” class is clicked.

Fork me on GitHub