RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment

Create an Image Grid Gallery With WordPress Shortcode

Create an Image Grid Gallery With WordPress Shortcode

There's literally no end to the manner in which images might be rendered into a WordPress gallery, and how styling might be applied to the end result. So, we're going to write a shortcode for as many image rendering options that we can think of. We needed a library to showcase various styles to our clients so we figured our blog would be a good platform. Many of the shortcode functions we initially share will be modified versions of those that were originally posted to Internoetics.

Our first function will scan a directory for all images and render them into a responsive grid. We've also provided a function that will retrieve all images attached to a WordPress post (except for the featured image) and return them in the same responsive grid style.

The Result

1. Rendering Images From a Directory

Since I've defined a default directory where all image galleries are located, the shortcode of [bmgallerygrid dir="sample-woodstock"] returns the following gallery.

Depending upon the viewport width, the above gallery scales from 5 columns down to a single column (as seen on most mobile phones).

The shortcode of [bmgallerygrid dir="sample-branson" columns="2" link="1"] returns the following:

In this example I've included link="1" so that the image will link to the full resolution version of itself.

The most significant disadvantage of returning images from a directory is that there's complexity in adding descriptions. We can overcome this by way of a JSON gallery, XML file, or text file, but this functionality is reserved for future articles. However, adding a caption is easy to accomplish in WordPress.

2. Rendering Images Attached to a WP Post

The second function returns all images uploaded to a WordPress post or page. The beliefmedia_image_gallery_images() function is required from this page. The example below includes a few stylistic attributes to alter the appearance.

The shortcode of [bmgallerygrids columns="3" number="6" tilecolor="#F29603" fontcolor="ffffff" link="1"] returns the following:


Oct. 20, 1973. The opening of the Opera House, 14 years after construction began.


Oct. 20, 1973. Sir Roden and Lady Cutler, and Sir Robert and Lady Askin with Queen Elizabeth II and the Duke of Edinburgh at the opening of the Opera House.


Feb. 4, 1972. Minister for Public Works Davis Hughes and Premier Robert Askin tour the concert hall of the Sydney Opera House during construction. Hughes had forced Utzon's resignation five years earlier.


January 1968. Part of the shells which form the roof of the Sydney Opera House, still under construction after 10 years of work.


March 8, 1966. Architect Jorn Utzon after a press conference with a scale model of the Sydney Opera House.


March 3, 1966. Students protest and march from Sydney Opera House to Parliament House in Sydney after the resignation of architect Jorn Utzon.

Note that I've only included 6 images. I've also altered the default tile and text color. The entire gallery is included as a sample here.

WordPress Shortcode

The first function scans a directory for all images and returns a gallery.

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

1
<?php 
2
/*
3
 Create a Responsive Grid Image Gallery From All Images in a Directory With PHP
4
 http://www.beliefmedia.com/code/php-snippets/image-grid-gallery-php
5
 http://www.beliefmedia.com/image-grid-gallery (WP Shortcode)
6
*/
7
 
8
function beliefmedia_grid_gallery($atts) {
9
 
10
  $atts = shortcode_atts(array(
11
    'default_dir'  => '/home/public_html/images/gallery/',
12
    'dir'  => 'sample-woodstock',
13
    'columns'  => '5',
14
    'url'  => 'http://www.YourDomain.com/images/gallery/',
15
    'link'  => 0,
16
    'number'  => 0,
17
    'random'  => 0,
18
 
19
    /* Viewport */
20
    'width_1' => '450',
21
    'width_2' => '560',
22
    'width_3' => '960',
23
 
24
    /* Basic style */
25
    'color' => 'ffffff',
26
    'fontcolor' => '000000',
27
    'fontweight' => 'normal',
28
    'fontsize' => '1.0',
29
    'tilecolor' => 'F8F8F8',
30
 
31
    /* Padding */
32
    'padding_around' => '10', /* 15 */
33
    'padding_between' => '10', /* 15 */
34
    'padding_bottom' => '5', /* 5 */
35
 
36
    /* Cache */
37
    'cache' => 3600 * 24 * 2
38
  ), $atts);
39
 
40
  /* If a default directory defined */
41
  $atts['scan'] = ($atts['default_dir'] != '') ? rtrim($atts['default_dir'], '/') . '/' . ltrim($atts['dir'], '/') : $atts['dir'];
42
 
43
  /* Transient */
44
  $transient = 'bmgd' . md5(serialize($atts));
45
  $cachedposts = get_transient($transient);
46
 
47
  if ($cachedposts !== false) {
48
    return $cachedposts;
49
 
50
  } else {
51
 
52
  $style = '
53
<style>
54
    .bm-grid-' . $transient . ' {
55
      background: #' . ltrim($atts['color'], '#') . ';
56
      -webkit-column-count: 1;
57
      -webkit-column-gap: 10px;
58
      -webkit-column-fill: auto;
59
      -moz-column-count: 1;
60
      -moz-column-gap: 10px;
61
      -moz-column-fill: auto;
62
      column-count: 1;
63
      column-gap: ' . $atts['padding_between'] . 'px;
64
      column-fill: auto;
65
    }
66
 
67
    .bm-grid-item-' . $transient . ' {
68
      display: inline-block;
69
      color: #' . ltrim($atts['fontcolor'], '#') . ';
70
      font-weight: ' . $atts['fontweight'] . ';
71
      font-size: ' . rtrim($atts['fontsize'], 'em') . 'em;
72
      background: #' . ltrim($atts['tilecolor'], '#') . ';
73
      margin: 0 0 10px;
74
      padding: ' . $atts['padding_around'] . 'px;
75
      padding-bottom: ' . $atts['padding_bottom'] . 'px;
76
      -webkit-column-break-inside: avoid;
77
      -moz-column-break-inside: avoid;
78
      column-break-inside: avoid;
79
    }
80
 
81
    .bm-hr-grid-' . $transient . ' {
82
      display: block;
83
      height: 1px;
84
      border: 0;
85
      border-top: 1px solid #ccc;
86
      margin: .5em 10px;
87
      padding: 0;
88
    }
89
 
90
    .bm-grid-img-' . $transient . ' {
91
      width: 100%
92
    }
93
 
94
    .bm_p_grid-' . $transient . ' {
95
      margin: 10px;
96
      font-size: .8em;
97
      font-family: arial;
98
      line-height: 1.5em;
99
    }
100
 
101
    @media (min-width: ' . $atts['width_1'] . 'px) {
102
      .bm-grid-' . $transient . ' {
103
        -webkit-column-count: 2;
104
        -moz-column-count: 2;
105
        column-count: 2;
106
      }
107
    }
108
 
109
    @media (min-width: ' . $atts['width_2'] . 'px) {
110
      .bm-grid-' . $transient . ' {
111
        -webkit-column-count: 3;
112
        -moz-column-count: 3;
113
        column-count: 3;
114
      }
115
    }
116
 
117
    @media (min-width: ' . $atts['width_3'] . 'px) {
118
      .bm-grid-' . $transient . ' {
119
        -webkit-column-count: ' . $atts['columns'] . ';
120
        -moz-column-count: ' . $atts['columns'] . ';
121
        column-count: ' . $atts['columns'] . ';
122
      }
123
    }
124
    </style>
125
 
126
';
127
 
128
  /* Scan all images in the image directory */
129
  $image_array = glob(rtrim($atts['scan'], '/') . '/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
130
  if ($atts['number']) $image_array = array_slice($image_array, 0, $atts['number']);
131
  if ($atts['random']) shuffle($image_array);
132
 
133
  foreach ($image_array AS $image) {
134
    $image = rtrim($atts['url'], '/') . '/' . $atts['dir'] . '/' . basename($image);
135
    $return .= '<div class="bm-grid-item-' . $transient . '">';
136
    $return .= (!$atts['link']) ? '<img class="bm-grid-img-' . $transient . '" src="' . $image . '">' : '<a href="' . $image . '"><img class="bm-grid-img-' . $transient . '" src="' . $image . '"></a>';
137
    $return .= '</div>';
138
  }
139
 
140
  $return = '<div class="bm-grid-' . $transient . '">' . $style . $return . '</div>';
141
 
142
  set_transient($transient, $return, $atts['cache']);
143
  return $return;
144
 }
145
}
146
add_shortcode('bmgallerygrid', 'beliefmedia_grid_gallery');

If you require shortcode to work in a sidebar widget, you'll have to enable the functionality with a filter. If you're using our custom functions plugin, you'll have that feature enabled by default.

■ ■ ■

The second function retrieves all post images (except the featured image) and returns the grid gallery. The function requires the beliefmedia_image_gallery_images() function as provided on this page.

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

1
<?php 
2
/*
3
 Create a Responsive Grid Image Gallery From All Images in a Directory With PHP
4
 http://www.beliefmedia.com/code/php-snippets/image-grid-gallery-php
5
 http://www.beliefmedia.com/image-grid-gallery (WP Shortcode)
6
*/
7
 
8
function beliefmedia_grid_post_gallery($atts) {
9
 
10
  $atts = shortcode_atts(array(
11
    'id'  => false,
12
    'columns'  => '5',
13
    'link'  => 0,
14
    'caption'  => 1,
15
    'number'  => 0,
16
 
17
    /* Padding */
18
    'padding_around' => '10', /* 15 */
19
    'padding_between' => '10', /* 15 */
20
    'padding_bottom' => '5', /* 5 */
21
 
22
    /* Viewport */
23
    'width_1' => '450',
24
    'width_2' => '560',
25
    'width_3' => '960',
26
 
27
    /* Basic style */
28
    'color' => 'ffffff',
29
    'fontcolor' => '000000',
30
    'fontweight' => 'normal',
31
    'fontsize' => '1.0',
32
    'tilecolor' => 'F8F8F8',
33
 
34
    /* Cache */
35
    'cache' => 3600 * 24 * 2
36
  ), $atts);
37
 
38
  /* Transient */
39
  $transient = 'bmgp' . md5(serialize($atts));
40
  $cachedposts = get_transient($transient);
41
 
42
  if ($cachedposts !== false) {
43
    return $cachedposts;
44
 
45
  } else {
46
 
47
  $style = '
48
<style>
49
    .bm-grid-' . $transient . ' {
50
      background: #' . ltrim($atts['color'], '#') . ';
51
      -webkit-column-count: 1;
52
      -webkit-column-gap: 10px;
53
      -webkit-column-fill: auto;
54
      -moz-column-count: 1;
55
      -moz-column-gap: 10px;
56
      -moz-column-fill: auto;
57
      column-count: 1;
58
      column-gap: ' . $atts['padding_between'] . 'px;
59
      column-fill: auto;
60
    }
61
 
62
    .bm-grid-item-' . $transient . ' {
63
      display: inline-block;
64
      color: #' . ltrim($atts['fontcolor'], '#') . ';
65
      font-weight: ' . $atts['fontweight'] . ';
66
      font-size: ' . rtrim($atts['fontsize'], 'em') . 'em;
67
      background: #' . ltrim($atts['tilecolor'], '#') . ';
68
      margin: 0 0 10px;
69
      padding: ' . $atts['padding_around'] . 'px;
70
      padding-bottom: ' . $atts['padding_bottom'] . 'px;
71
      -webkit-column-break-inside: avoid;
72
      -moz-column-break-inside: avoid;
73
      column-break-inside: avoid;
74
    }
75
 
76
    .bm-hr-grid-' . $transient . ' {
77
      display: block;
78
      height: 1px;
79
      border: 0;
80
      border-top: 1px solid #ccc;
81
      margin: .5em 10px;
82
      padding: 0;
83
    }
84
 
85
    .bm-grid-img-' . $transient . ' {
86
      width: 100%
87
    }
88
 
89
    .bm_p_grid-' . $transient . ' {
90
      margin: 10px;
91
      font-size: .8em;
92
      font-family: arial;
93
      line-height: 1.5em;
94
    }
95
 
96
    @media (min-width: ' . $atts['width_1'] . 'px) {
97
      .bm-grid-' . $transient . ' {
98
        -webkit-column-count: 2;
99
        -moz-column-count: 2;
100
        column-count: 2;
101
      }
102
    }
103
 
104
    @media (min-width: ' . $atts['width_2'] . 'px) {
105
      .bm-grid-' . $transient . ' {
106
        -webkit-column-count: 3;
107
        -moz-column-count: 3;
108
        column-count: 3;
109
      }
110
    }
111
 
112
    @media (min-width: ' . $atts['width_3'] . 'px) {
113
      .bm-grid-' . $transient . ' {
114
        -webkit-column-count: ' . $atts['columns'] . ';
115
        -moz-column-count: ' . $atts['columns'] . ';
116
        column-count: ' . $atts['columns'] . ';
117
      }
118
    }
119
    </style>
120
 
121
';
122
 
123
  /* Get array of images */
124
  global $post;
125
  $id = ($atts['id'] == '') ? $post->ID : $atts['id'];
126
  $image_array = beliefmedia_image_gallery_images($id);
127
  if ($atts['number']) $image_array = array_slice($image_array, 0, $atts['number']);
128
 
129
  foreach ($image_array AS $image) {
130
    $return .= '<div class="bm-grid-item-' . $transient . '">';
131
    $return .= (!$atts['link']) ? '<img class="bm-grid-img-' . $transient . '" src="' . $image['src'] . '" title="' . $image['title'] . '">' : '<a href="' . $image['full'] . '"><img class="bm-grid-img-' . $transient . '" src="' . $image['src'] . '" title="' . $image['title'] . '"></a>';
132
    if ($atts['caption']) $return .= '
133
<hr>
134
 
135
' . $image['caption'] . '';
136
    $return .= '</p></div>';
137
  }
138
 
139
  $return = '<div class="bm-grid-' . $transient . '">' . $style . $return . '</div>';
140
 
141
  set_transient($transient, $return, $atts['cache']);
142
  return $return;
143
 }
144
}
145
add_shortcode('bmgallerygrids', 'beliefmedia_grid_post_gallery');

If you require shortcode to work in a sidebar widget, you'll have to enable the functionality with a filter. If you're using our custom functions plugin, you'll have that feature enabled by default.

Shortcode Attributes

We've limited attribute options as best we could. If required you can obviously code in your own changes.

default_dir

Used in the first function that scans a directory, you may specify a default root directory. In our case we have a gallery directory that we've referenced. All image galleries will be a sub-directory of 'gallery'.

dir

The dir of your images. If default_dir is defined it'll simply be your directory name. Otherwise it's the full path.

id

For our second function (rendering images attached to a post) we'll use the current post by default. To return images from another post, use post="1234" (where 1234 is the post ID.

columns

The number of image columns to return. See also the viewport information as this will determine how many columns are actually displayed.

url

The url is the URL to your gallery directory. When we return the image we use the basename so require a full URL reference. If you have defined a default_dir then the URL will be a set and forget attribute.

link

If you choose to link to the full version of the image use link="1".

number

If you choose to limit the number of images returned use number="10" (where 10 is the number of images you want displayed).

random

To randomize the returned images use random='1".

width_1, width_2 and width_3

For scaling on mobile devides or smaller screens, the widths refer to the viewport that'll scale the columns to 3 columns and then 1 column.

color & tilecolor

To alter the color of the background container use tile container use color="DBDBDB" (we've done this to match the color of our page background). To alter the tile color (as demonstrated in our Sydney Opera House gallery), use tilecolor="#09A3E2" (again, as we've done in the Opera House Gallery to match our blue menu/sidebar color).

fontcolor, fontweight, fontsize

The fontcolor, fontweight, and fontsize are used to style the text in each tile container.

padding_around, padding_between, and padding_bottom

The padding_around, padding_between, and padding_bottom attributes alter the padding associated with each tile.

cache

To avoid the overhead associated with processing the gallery and building the HTML, we cache results for a period of time. Alter as required. Consider using Simple Cache as a database alternative.

PHP Function

Used outside of WordPress the following PHP Function may be used. An example of the output can be found here.

Considerations

  • While we've used directory and post images for this particular example, any array of images may be used. We'll be posting additional examples (likely with alternate gallery formats) for Google Plus images, YouTube videos/thumbnails, Instagram images and so on. Like our lonely page on Facebook for updates.
  • A handy use for this function (that we use all the time while in the field) is to FTP images directly to a directory while out-and-about. Those images are shared to a post effortlessly. Some cameras will automatically facilitate the FTP upload, and others will upload to cloud storage, meaning that images can be displayed in a similar manner.
  • In the second WordPress function the image title is provided in the resulting array alongside the image caption. You may code the title in if you choose (by default the image is shown as the image title on mouseover).
  • Further to the point above: always, always, always provide a title and caption and/or description for images uploaded to the WP library. Our function requires captions only.
  • A previous version of this function (using rows rather than CSS) was published on Internoetics; it utilized timthumb for the scaling of images... hardly an ideal solution. We would, however, encourage the use of a library to scale images as required - particularly if you're after a square ordered grid. An alternative method might be the creation of custom WP image sizes.

Download

The function beliefmedia_image_gallery_images() is required, and it's included in the shortcode download. If you already have it installed (or you're a client using the BeliefMedia WordPress plugin), ensure you don't include it a second time.


Title: Create an Image Grid Gallery (WP Shortcode)
Description: Create a responsive grid image gallery (of all post images or images from a directory) with WordPress shortcode. Numerous styling/rendering options apply.
  Download • Version 0.2, 2.0K, zip, Category: WordPress Shortcodes
PHP Code & Snippets, (1.1K)    

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  AUS Eastern Standard Time (Virginia)

  Want to have a chat?
 

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment