6

Is there way to control the gallery default “Link to” setting? Using the image_default_link_type filter within a functions.php file works on inserting single images into posts but it doesn't seem to have any effect on galleries...

  • Hi @Eugene, thank you for such a quick response. I tried the example you provided verbatim on a clean install of 3.6.1 and also with “none” changed to “file” which is the result I was originally after. I pasted this code at the end of twenty-twelve’s functions file with no result whatsoever. No warnings with wp-debug enabled either. Did I miss something? Thanks so much for your help! – Brian Wayne Sep 24 '13 at 0:19
  • Have you created a gallery post? – Eugene Manuilov Sep 24 '13 at 6:57
  • So you want [gallery] to behave like [gallery link="file"] ? Might be a duplicate of this question – birgire Sep 24 '13 at 9:56
  • Hey @Eugene, I created the post but never actually clicked the images! How dumb was that? I got hung up on the fact that the “link to” under Gallery Settings still said “Attachment Page”. This works perfectly. Thank you so much! – Brian Wayne Sep 24 '13 at 15:28
1

Unfortunately there is no legal way to control it. But there is a dirty way to do it... If you select this route, then you will need to :

  • clone the standard gallery_shortcode function
  • add a default value for $attr['link'] option
  • hook your cloned function into post_gallery filter

The final result will look like this:

add_filter( 'post_gallery', 'wpse8170_gallery_shortcode', 10, 2 );
function wpse8170_gallery_shortcode( $output, $attr ) {
    $post = get_post();

    static $instance = 0;
    $instance++;

    // override default link settings
    if ( empty(  $attr['link'] ) ) {
        $attr['link'] = 'none'; // set your default value here
    }

    if ( !empty( $attr['ids'] ) ) {
        // 'ids' is explicitly ordered, unless you specify otherwise.
        if ( empty( $attr['orderby'] ) )
            $attr['orderby'] = 'post__in';
        $attr['include'] = $attr['ids'];
    }

    // We're trusting author input, so let's at least make sure it looks like a valid orderby statement
    if ( isset( $attr['orderby'] ) ) {
        $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
        if ( !$attr['orderby'] )
            unset( $attr['orderby'] );
    }

    extract(shortcode_atts(array(
        'order'      => 'ASC',
        'orderby'    => 'menu_order ID',
        'id'         => $post ? $post->ID : 0,
        'itemtag'    => 'dl',
        'icontag'    => 'dt',
        'captiontag' => 'dd',
        'columns'    => 3,
        'size'       => 'thumbnail',
        'include'    => '',
        'exclude'    => ''
    ), $attr, 'gallery'));

    $id = intval($id);
    if ( 'RAND' == $order )
        $orderby = 'none';

    if ( !empty($include) ) {
        $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );

        $attachments = array();
        foreach ( $_attachments as $key => $val ) {
            $attachments[$val->ID] = $_attachments[$key];
        }
    } elseif ( !empty($exclude) ) {
        $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
    } else {
        $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
    }

    if ( empty($attachments) )
        return '';

    if ( is_feed() ) {
        $output = "\n";
        foreach ( $attachments as $att_id => $attachment )
            $output .= wp_get_attachment_link($att_id, $size, true) . "\n";
        return $output;
    }

    $itemtag = tag_escape($itemtag);
    $captiontag = tag_escape($captiontag);
    $icontag = tag_escape($icontag);
    $valid_tags = wp_kses_allowed_html( 'post' );
    if ( ! isset( $valid_tags[ $itemtag ] ) )
        $itemtag = 'dl';
    if ( ! isset( $valid_tags[ $captiontag ] ) )
        $captiontag = 'dd';
    if ( ! isset( $valid_tags[ $icontag ] ) )
        $icontag = 'dt';

    $columns = intval($columns);
    $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
    $float = is_rtl() ? 'right' : 'left';

    $selector = "gallery-{$instance}";

    $gallery_style = $gallery_div = '';
    if ( apply_filters( 'use_default_gallery_style', true ) )
        $gallery_style = "
        <style type='text/css'>
            #{$selector} {
                margin: auto;
            }
            #{$selector} .gallery-item {
                float: {$float};
                margin-top: 10px;
                text-align: center;
                width: {$itemwidth}%;
            }
            #{$selector} img {
                border: 2px solid #cfcfcf;
            }
            #{$selector} .gallery-caption {
                margin-left: 0;
            }
            /* see gallery_shortcode() in wp-includes/media.php */
        </style>";
    $size_class = sanitize_html_class( $size );
    $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
    $output = apply_filters( 'gallery_style', $gallery_style . "\n\t\t" . $gallery_div );

    $i = 0;
    foreach ( $attachments as $id => $attachment ) {
        if ( ! empty( $attr['link'] ) && 'file' === $attr['link'] )
            $image_output = wp_get_attachment_link( $id, $size, false, false );
        elseif ( ! empty( $attr['link'] ) && 'none' === $attr['link'] )
            $image_output = wp_get_attachment_image( $id, $size, false );
        else
            $image_output = wp_get_attachment_link( $id, $size, true, false );

        $image_meta  = wp_get_attachment_metadata( $id );

        $orientation = '';
        if ( isset( $image_meta['height'], $image_meta['width'] ) )
            $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';

        $output .= "<{$itemtag} class='gallery-item'>";
        $output .= "
            <{$icontag} class='gallery-icon {$orientation}'>
                $image_output
            </{$icontag}>";
        if ( $captiontag && trim($attachment->post_excerpt) ) {
            $output .= "
                <{$captiontag} class='wp-caption-text gallery-caption'>
                " . wptexturize($attachment->post_excerpt) . "
                </{$captiontag}>";
        }
        $output .= "</{$itemtag}>";
        if ( $columns > 0 && ++$i % $columns == 0 )
            $output .= '<br style="clear: both" />';
    }

    $output .= "
            <br style='clear: both;' />
        </div>\n";

    return $output;
}
17

There is an easier solution now:

function my_gallery_default_type_set_link( $settings ) {
    $settings['galleryDefaults']['link'] = 'file';
    return $settings;
}
add_filter( 'media_view_settings', 'my_gallery_default_type_set_link');

They added a filter to customize this default value (and other values related to the new media upload popup) in WP 4.0 (trac).

5

Old question but still getting search traffic so for everyone else:

You can accomplish what you describe by filtering the gallery shortcode attributes. Also useful if you want to change the default image size, columns, etc.

function gallery_should_link_to_files($out, $pairs, $atts)
{
    $atts = shortcode_atts( array( 
    'link' => 'file' 
    ), $atts );
    $out['link'] = $atts['link'];
    return $out;
}
add_filter('shortcode_atts_gallery', 'gallery_should_link_to_files', 10, 3);

The filter seems poorly documented in the Codex : http://codex.wordpress.org/Function_Reference/shortcode_atts_gallery

Still, the option to modify the 'link' attribute was added early in 2013 : https://core.trac.wordpress.org/changeset/25665/trunk

  • 1
    the only example of all the current answers that worked for me. must be inserted e.g. in functions.php of active theme. – CodingYourLife Jun 14 '16 at 19:47
1

It fact works. As denoted above, in the sidebar it will appear as though the gallery is linking to "Attachment Page". However, once you publish your post and click on the image you will notice that it is in fact linked to the media file.

I took this code a step further and created a plugin. This is functionality that I want to stay site specific instead of theme specific.

To create the plugin I followed the simple instructions on this page. I created a file named gallery-link-to-file.php in the wp-content/plugins directory. I then pasted the above code into it and changed $attr['link'] = 'none'; to $attr['link'] = 'file';

I then activated the plugin and it worked like a charm.

1

This is my working example for WordPress 5.0 (Gutenberg)!

function gallery_template_to_posts() {
    $post_type_object = get_post_type_object( 'post' );
    $post_type_object->template = array(
        array( 'core/gallery', array(
            'linkTo' => 'media',
        ) ),
    );
}
add_action( 'init', 'gallery_template_to_posts' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.