Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force WordPress Gallery to Use Media File Link instead of Attachment Link

Is there a filter or hook to force WordPress Galleries to use the Media File Link instead of the Attachment Link. I can not trust my client to manually switch the setting while creating the gallery. http://cl.ly/image/2g1L1G2c2222

Brings up another issue of why Media File is not the default type.

like image 849
Darren Cooney Avatar asked Dec 16 '22 01:12

Darren Cooney


2 Answers

You can basically ovveride the default gallery shortcode .

remove_shortcode('gallery', 'gallery_shortcode'); // removes the original shortcode
    add_shortcode('gallery', 'my_awesome_gallery_shortcode'); // add your own shortcode

    function my_awesome_gallery_shortcode($attr) {
    $output = 'Codex is your friend' ;
    return $output;
}

Inside the custom function you could set whatever you want .. look at the original gallery shortcode .

Another way is to actually filter the attributes ( if you will go to the above link, you will see a filter hook )

add_shortcode( 'gallery', 'my_gallery_shortcode' );

function my_gallery_shortcode( $atts )
{
    $atts['link'] = 'file';
    return gallery_shortcode( $atts );
}
like image 106
Obmerk Kronen Avatar answered May 12 '23 03:05

Obmerk Kronen


Obmerk Kronen's answer is very neat and works most of the situations. However, recently I ran across a problem on one of my client's websites, that couldn't be solved that way. I actually don't know, why. I suppose it was because of another gallery plugin, that was tampering with the same shortcode.

So, I found a different solution, not that neat, but working. Here, maybe someone will find this helpfull:

add_filter('the_content','galleries_attachments_to_media_links');
function galleries_attachments_to_media_links( $content ) {
/**
 * Overrides gallery shortcode settings and forces media file loading, if gallery set to attachment link
 */
if(strpos($content,'[gallery') !== FALSE) {
    $content = str_replace('[gallery','[gallery link="file"',$content);
    return $content;
}
else return $content;
}

It looks like even if a gallery is already set to media file, it's not a problem and WordPress executes the shortcode properly.

like image 26
ToNo Avatar answered May 12 '23 04:05

ToNo