How can I make all gallery images to open in a new window?

(Update 04.05.2012: Include captions)

Let’s start with a solution …

There is no filter especially for gallery image links. There is also no filter for the gallery shortcode output. So we have to fake one:

add_action( 'after_setup_theme', 'wpse_50911_replace_img_shortcodes' );

/**
 * Replace the default shortcode handlers.
 *
 * @return void
 */
function wpse_50911_replace_img_shortcodes()
{
    remove_shortcode( 'gallery', 'gallery_shortcode' );
    add_shortcode( 'gallery', 'wpse_50911_gallery_shortcode' );

    remove_shortcode( 'caption', 'img_caption_shortcode' );
    remove_shortcode( 'wp_caption', 'img_caption_shortcode' );
    add_shortcode( 'caption', 'wpse_50911_caption_shortcode' );
    add_shortcode( 'wp_caption', 'wpse_50911_caption_shortcode' );
}

What it does: It replaces the default shortcode handlers for , and . Now we have to write the replacement functions. That’s actually pretty easy because we let WordPress do (almost) all the work:

/**
 * Add the new attribute to the gallery.
 *
 * @param  array $attr Shortcode attributes
 * @return string
 */
function wpse_50911_gallery_shortcode( $attr )
{
    // Let WordPress create the regular gallery …
    $gallery = gallery_shortcode( $attr );
    // … and add the target attribute to all links.
    $gallery = str_replace( '<a ', '<a target="_blank" ', $gallery );

    return $gallery;
}

/**
 * Add the new attribute to the caption.
 *
 * @param  array  $attr    Shortcode attributes
 * @param  string $content Caption text
 * @return string
 */
function wpse_50911_caption_shortcode( $attr, $content = NULL )
{
    $caption = img_caption_shortcode( $attr, $content );
    $caption = str_replace( '<a ', '<a target="_blank" ', $caption );
    return $caption;
}

What it does: It’s delegating the shortcode work to the native WordPress functions. Then it takes the output and inserts the attribute target="_blank". And then it returns the output to the page.

Done. When you insert a gallery or a caption make sure the links point to the file URI, not to an attachment page.

Caveats

  • The new window will break the back button. That’s very annoying for users of screen readers or some mobile devices.
  • Safari mobile once could not open more than seven windows (not sure if this still true) and just refused to open a new one when the limit was reached. A click on such a link may do nothing.
  • Some users just hate forced new tabs/windows. I’m one of those. 🙂
  • If you use another plugin to change the gallery output it will probably not work anymore.

Do not use this code … unless you are forced with a lot of money to do it.

Leave a Comment