overriding default gallery shortcode and fetch the attachments easily in wordpress


Shortcodes are a sort of plugin used to display different contents, but the only difference with the traditional plugins is that shortcodes are embeddable by the authors almost anywhere in the content block. Wordress has an extensive list of community developed shortcodes as well as a few backed/developed by Automattic themselves. Among those, gallery shortcode is one of the most popular ones and it comes packed with wordpress. It takes the id of the attachment as argument and then generates a minimal gallery.

But there are problems with the default gallery shortcode. The markup that it generates is not designer friendly and you can’t style it easily. Moreover, if you want to give it a sleek look, add some lightbox functionality then you will need to override it.

In this article, I will show you how you can write a new shortcode which hooks the gallery, parse the arguments and fetch the attachments and finally genrate an unordered list <ul></ul> out of it.

hook it, hook it!

the following codeblock will create a hook and invoke our new shortcode instead of the bundled gallery shortcode. It will also register a new thumbnail size, 150x150px

<?php
function new_gallery($array) {
    //fetch attachments here
}
add_shortcode('gallery', 'new_gallery');
add_image_size('gallery-thumb', 150, 150,true);

now whenever someone writes a gallery shortcode in the content, for example [ gallery ids=12,17,34 ] this function we just wrote, new_gallery() will be called.

fetch the attachments and display the list

Alright, now we need to fetch the attachments from the attachment ids passed via ids argument. We can do it like this

<?php
function new_gallery($array) {

    $ids = explode(",",$array['ids']);
    $posts=array();

    $args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' =>'any', 'post_parent' => $post->ID ); 

    $attachments = get_posts($args);
    if ($attachments) {
        echo '<ul>';

        foreach ( $attachments as $attachment ) {
            $posts[$attachment->id]=$attachment;
        }
        foreach ( $ids as $id ) {
            $attachment = $posts[$id];
            $medium_thumbnail = wp_get_attachment_image($attachment->ID, $size='medium', $icon = false);
            $custom_thumbnail_image = wp_get_attachment_image($attachment->ID, $size='gallery-thumb');

            echo "
            <li>
                <a href='{$medium_thumbnail}'> {$custom_thumbnail_image} </a>
            </li>    
            ";
        }
        echo '</ul>';
    }
    wp_reset_postdata();
}

add_shortcode('gallery', 'new_gallery');
add_image_size('gallery-thumb', 150, 150,true);

The tricky part was calling get_posts() with the two arguments numberofposts = -1 and post_type = attachment. The -1 for numberofposts returns all images attached with the current post. But as the gallery shortcode might have used only a few among them, so we run the second for{} loop for only those attachments used within the scope of current gallery call.

Also, it took me a while first time to find the appropriate function for retrieving the attachment image by predefined dimension shortcuts, which is wp_get_attachment_image. So you may want to check Codex as well for the reference of wordpress functions, filters and hooks.

Shameless Plug

We develop beautiful Admin Panel templates for the web application developers. Our recent product is “Bolt” which is responsive and built on top of Twitter’s bootstrap. Give it a try and let us know how do you like it.

Bolt Responsive Admin Panel Template for Developers

Bolt Responsive Admin Panel Template for Developers

About these ads

4 thoughts on “overriding default gallery shortcode and fetch the attachments easily in wordpress

  1. This is exactly what I am looking for. However, being a bit of a PHP novice, I’m unsure how to word this bit correctly:

    <li>
    <a href='{$medium_thumbnail}'> $custom_thumbnail_image} </a>
    </li>
    

    I’ve tried this to no avail:

    <a href='$medium_thumbnail'> <img src='$custom_thumbnail_image' /></a>
    

    Any help, much appreciated.

    • Hope you had noticed the missing brace before $custom_thumbnail_image}
      I have added that in my code and hopefully it will fix your problem this time. Thanks

  2. Thanks for your prompt reply. Yes I had noticed it, but yet it fails when rectified. Here is what it is outputting:

    <ul>
                <li>
                    <a href=''></a>
                </li> 
                <li>
                    <a href=''></a>
                </li>    
                <li>
                    <a href=''></a>
                </li>    
    </ul>
    
  3. Have you tried this and got it to work? Any help much appreciated.

    It outputs the correct number of tags for the amount of photos their are in my gallery but there is nothing between the tags. Please help?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s