admin管理员组

文章数量:1122832

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...

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...

Share Improve this question edited Sep 23, 2013 at 20:19 Eugene Manuilov 11.4k4 gold badges44 silver badges50 bronze badges asked Sep 23, 2013 at 20:09 Brian WayneBrian Wayne 1231 gold badge2 silver badges5 bronze badges 4
  • 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 Commented Sep 24, 2013 at 0:19
  • Have you created a gallery post? – Eugene Manuilov Commented Sep 24, 2013 at 6:57
  • So you want [gallery] to behave like [gallery link="file"] ? Might be a duplicate of this question – birgire Commented Sep 24, 2013 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 Commented Sep 24, 2013 at 15:28
Add a comment  | 

7 Answers 7

Reset to default 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;
}

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).

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);

Edit Jan 2020: As pointed out by @felwithe in comments, this code would go in your wp-includes/shortcodes.php, for example. It still works in current Wordrpess !

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

Tomas's answer actually contain's the key to change default linking (for Gutenberg). Does not affect already created galleries.

The best way how I was able to implement it, was creating a new edited variation of needed block (gallery), and set it as default. That way the old gallery was replaced by new, edited one.

Register new variation by creating js file in the theme's js folder:

// Gallery block
wp.blocks.registerBlockVariation(
   'core/gallery', {
      isDefault: true,
      attributes: {
        linkTo: 'media',
      }
   }
);
// Image block
wp.blocks.registerBlockVariation(
   'core/image', {
      isDefault: true,
      attributes: {
        linkDestination: 'media',
      }
   }
);

Enqueue it in fuctions.php

function new_gallery() {
    wp_enqueue_script('new-gallery', get_template_directory_uri() . '/js/gallery-var.js',
        array( 'wp-blocks', 'wp-dom-ready', 'wp-edit-post' )
    );
}
add_action( 'enqueue_block_editor_assets', 'new_gallery' );

There is probably a php way to do this too, but for some reason there is only register_block_style mentioned in the documentation https://developer.wordpress.org/block-editor/developers/filters/block-filters/

I am starting to like gutenberg more and more :)

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' );

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.

It is possible to change the default "link to" setting in the core/gallery Gutenberg block with PHP only (Wordpress 6.6):

function my_block_type_metadata($settings, $metadata)
{
    if ($settings['name'] == 'core/gallery') {
        $settings['supports']['align'] = false;
        $settings['attributes']['columns']['maximum'] = 1;
        $settings['attributes']['linkTo']['default'] = 'media';
    }
}
add_filter('block_type_metadata_settings', 'my_block_type_metadata', 10, 2);

See the "block filters" documentation.

本文标签: imagesOveride Gallery Default Link to Settings