Using WordPress ‘gallery_shortcode()’ PHP function

The gallery_shortcode() WordPress PHP function is used to build the output for the Gallery Shortcode, allowing you to display WordPress images on a post.

Usage

To use the function, you would typically call it with the gallery attributes as an argument:

gallery_shortcode($attr);

Here’s a custom example:

gallery_shortcode(array(
    'order' => 'DESC',
    'orderby' => 'ID',
    'columns' => 4,
    'size' => 'medium',
    'ids' => '1,2,3,4'
));

In this example, the images with IDs 1, 2, 3, and 4 will be displayed in a gallery of 4 columns. The images will be ordered by their ID in descending order, and their size will be medium.

Parameters

  • $attr array (Required): Attributes of the gallery shortcode.
    • order (string): Order of the images in the gallery. Default is ‘ASC’. It can be ‘ASC’ or ‘DESC’.
    • orderby (string): The field to use when ordering the images. Default is ‘menu_order ID’. It can accept any valid SQL ORDERBY statement.
    • id (int): Post ID.
    • itemtag (string): HTML tag to use for each image in the gallery. Default is ‘dl’, or ‘figure’ when the theme registers HTML5 gallery support.
    • icontag (string): HTML tag to use for each image’s icon. Default is ‘dt’, or ‘div’ when the theme registers HTML5 gallery support.
    • captiontag (string): HTML tag to use for each image’s caption. Default is ‘dd’, or ‘figcaption’ when the theme registers HTML5 gallery support.
    • columns (int): Number of columns of images to display. Default is 3.
    • size (string|int): Size of the images to display. Accepts any registered image size name, or an array of width and height values in pixels (in that order). Default is ‘thumbnail’.
    • ids (string): A comma-separated list of IDs of attachments to display. Default is empty.
    • include (string): A comma-separated list of IDs of attachments to include. Default is empty.
    • exclude (string): A comma-separated list of IDs of attachments to exclude. Default is empty.
    • link (string): What to link each image to. Default is empty (links to the attachment page). Accepts ‘file’, ‘none’.

More information

See WordPress Developer Resources: gallery_shortcode()

Examples

Example 1

This code displays a gallery with images ordered in ascending order.

gallery_shortcode(array('order' => 'ASC'));

Example 2

This code creates a gallery where images are ordered by the field ‘ID’.

gallery_shortcode(array('orderby' => 'ID'));

Example 3

Here we set the HTML tags to be used for each image, the image’s icon, and each image’s caption.

gallery_shortcode(array('itemtag' => 'figure', 'icontag' => 'div', 'captiontag' => 'figcaption'));

Example 4

This example shows how to display a gallery with a specified number of columns and a specified image size.

gallery_shortcode(array('columns' => 4, 'size' => 'medium'));