WPLake > Blog > ACF Gallery Field: Usage and Display Guide
  • Deutsch
  • Español
  • Français
  • Italiano

ACF Gallery Field: Usage and Display Guide

Time to read: 7 mins

-

ACF Plugins Tutorials

-

Updated 26.01.24

Learn how the Gallery field works and behaves. Display a gallery manually or using smart templates, and take advantage of the Masonry and Lightbox options.

Table of Contents

About the Gallery field

#link copied

Advanced Custom Fields is one of the best plugins for managing meta fields and Custom Post Types (CPTs). The Gallery field is one of the ACF field types, and it enables you to choose multiple images for a single field directly from the WordPress Media Library.

This is particularly useful when creating various types of galleries or when you need to showcase a custom collection of images on a page. Unlike the ACF Image field, which supports only a single image, the ACF Gallery field offers the flexibility of selecting and displaying multiple images.

Add a Gallery field type in Advanced Custom Fields (ACF)
You can add multiple images to the ACF Gallery field when editing your page.
You can easily remove images by clicking the 'x' and drag them to reorder as needed.

Extensions

#link copied

For images, the allowed extensions are .jpg, .jpeg, .png, .gif, and .ico. You can find a list of allowed extensions for all file types on the related wordpress.org page. If you wish to allow uploading of file types such as .svg, you'll need to utilize special hooks.

Note: It's not possible to upload non-image files to the ACF Image field. For file types like .doc or .pdf, even with the use of hooks, you should consider using the ACF File field, which is designed for this purpose.

If you're interested in learning the hook names to add support for additional image extensions beyond those listed above, we provide a code snippet that enables .svg uploading on your website. You can customize it for your desired extension or use it as is for .svg. The code can be added to your functions.php file. Alternatively, you can use the Safe SVG plugin.

<?php
         add_filter('upload_mimes', function ($mimes) {
            $mimes['svg'] = 'image/svg+xml';

            return $mimes;
        });

        add_filter('wp_check_filetype_and_ext', function ($data, $file, $filename, $mimes) {
            $filetype = wp_check_filetype($filename, $mimes);

            return [
                'ext' => $filetype['ext'],
                'type' => $filetype['type'],
                'proper_filename' => $data['proper_filename']
            ];
        }, 10, 4);

Return formats

#link copied

The ACF Gallery field offers three different Return Formats: Image Array, Image URL, and Image ID. This mirrors the Image field, but the response is consistently an array. Within the array, items have a type corresponding to the chosen Return Format. It's important to note that this does not impact the field's appearance or the options available to site administrators. Instead, the Gallery Return Format governs the data you receive in the code, specifically when you request the ACF Gallery field from the WordPress database using the get_field function.

We recommend utilizing the 'Image ID' option for the best performance. It's the preferred choice. Conversely, we advise against using the 'Image URL' option unless you have a specific need for it. This option only provides the URL of the image without any additional details, which may not be sufficient for most use cases.

Behind the ACF scenes

#link copied

The ACF Gallery field functions much like the ACF Image field, but with one significant distinction: it stores an array of image IDs in the Post Meta of the respective page or post item. In contrast, the Image field stores only a single image ID.

In essence, the ACF Gallery field serves as an intermediary between the Media Library and you, the user. It offers an intuitive user interface for selecting multiple images from your Media Library. However, internally, it doesn't store the images individually. Instead, it utilizes a form of tagging or 'linking' to associate the images (or attachments) from the Media Library with the specific page or post.

Display Gallery field using Smart templates

#link copied

Let us introduce the Advanced Views addon.

Advanced Views provides smart templates for effortless content display. It comes with built-in post queries and automated template generation, enabling rapid development while maintaining flexibility.

Let's first clarify what we mean by 'templates' in the context of this plugin: Advanced Views templates are built on the Twig engine. You might be thinking, 'Not bad, but it still requires fetching fields via PHP and writing markup from scratch, not to mention reading Twig documentation'.

Here's where the plugin shines: "Smart templates". This means we don't have to fetch fields or create markup manually from scratch. The plugin provides a solid foundation that covers most use cases. If we require something specific, we can easily customize it. Isn't that nice?

Basics

#link copied

Now, let's take a basic look at how it works.

The plugin introduces two new Custom Post Types (CPTs): ACF View and ACF Card.

  • View for post data and Advanced Custom Fields
    We create a View and assign one or more post fields, the plugin then generates a shortcode that we'll use to display the field values to users. We can style the output with the CSS field included in every View.
  • Card for post selections
    We create a Card and assign posts (or CPT items), choose a View (that will be used to display each item) and the plugin generates a shortcode that we'll use to display the set of posts. The list of posts can be assigned manually or dynamically with filters.

The plugin offers us the convenience of working with familiar WordPress CPTs while taking care of querying and automatically generating Twig markup templates. You can find more information about the plugin's benefits here.

To follow along; install the Advanced Views plugin on your WordPress site and remember to activate it. You'll also need the ACF (free) plugin installed and active. Then continue to the next steps below.

Step 1. Creating a View

#link copied

When you activate the Advanced Views plugin, you'll notice a new item in your admin menu titled "Advanced Views."

Within the submenu, you'll find several items, but the one you'll need to use is called 'Advanced Views.'

ACF Views provides list management via the familiar interface.
Your list will have the same appearance, but it won't contain any View items.

Provide a name for your View. It can be anything that describes the View, as this name will be displayed in the list of Views, making it easier to identify. For example, we've named our View "Page gallery".

ACF Views allow to assign multiple fields within your View.

Assigning fields

#link copied

When assigning new fields to your View, click the 'Add Field' button and select your 'Group' from the dropdown menu. In my case, the group is labeled "Page fields." Next, choose the target Field from the dropdown; in this instance, we've selected "Page gallery."

Note: The field type is displayed in brackets for easy identification. This way, you can readily determine the type of any field in the dropdown.

In this case, you should see "(gallery)" in the dropdown. Proceed by selecting an 'Image Size' from the list; we've opted for 'Full'.

If you are using the Pro version of the plugin, you will also have access to Masonry and Lightbox options. Please refer to the screenshot below for reference.

Masonry and Lightbox options are exclusively available to Pro users.

Every View supports an unlimited number of ACF fields, but in our case, we'll assign only a single field.

Click the 'Publish' button to save and publish your View. Once your View is published, you'll notice that Shortcodes have been generated and are available in a block on the right side of your View edit screen. Each View has its unique shortcode with a unique ID (the shortcode structure is the same for all Views, but the arguments are unique).

[acf_views view-id="xxxx" name="x"]

Press the 'Copy to clipboard' button for the first shortcode.

Step 2. Paste the shortcode in place

#link copied

We're almost there, and now that everything is set up, we're ready to display the ACF Gallery field.

Visit your target page that contains the ACF Gallery field (ensure that you have attached a few images). Then, paste the copied shortcode anywhere you'd like within the page content. If you're using the Gutenberg editor, click on the plus button and select the "Shortcode" block from the list. Paste your shortcode into the block and click the 'Update' button to save your post/page.

Gutenberg block containing an Advanced Views shortcode.

Open the page to view the result. If everything was done correctly, you should see all the attached images from the ACF Gallery field displayed.

The ACF Gallery field is now displayed on the page using a shortcode (with a plain appearance).
Gallery with the Masonry option enabled (available in the Pro version only).
The lightbox option enables zooming for any image in the Gallery (available in the Pro version only).

If you can't see your gallery, follow these steps:

  1. Go back and edit the page.
  2. Confirm that you have attached some images to the ACF Gallery field.
  3. Reload the page.

If, for some reason, you still don't see anything, return to edit your View and ensure that you've selected the correct "Group" field from the list.

Display Gallery field with PHP code

#link copied

To display the Gallery field, we need to convert the selected images from the field into img tags.

The code will vary depending on the selected Return Type. Below, we've provided examples that can assist you in generating the output. However, please note that to transform it into an interactive gallery, you'll need to write your own CSS and JavaScript code.

1. PHP code to display the Gallery field with the "ID" Return Format:

<?php

// don't forget to replace 'gallery' with your field name
$images = get_field('gallery');
// can be one of the built-in sizes ('thumbnail', 'medium', 'large', 'full' or a custom size)
$size = 'full';
if ($images) {
    foreach ($images as $imageId) {
        echo wp_get_attachment_image($imageId, $size);
    }
}

2. PHP code to display the Gallery field with the "Array" Return Format:

<?php

// don't forget to replace 'gallery' with your field name
$images = get_field('gallery');
// can be one of the built-in sizes ('thumbnail', 'medium', 'large', 'full' or a custom size)
$size = 'full';
if ($images) {
    foreach ($images as $imageData) {
        // displays the image. Each %s in the string will be replaced with the related argument
        printf("<img src='%s' alt='%s'>",
            esc_url($imageData['sizes'][$size]), esc_attr($imageData['alt']));
    }
}

3. PHP code to display the Gallery field with the "URL" Return Format:

<?php

// don't forget to replace 'gallery' with your field name
$images = get_field('gallery');
if ($images) {
    foreach ($images as $imageURL) {
        // displays the image. Each %s in the string will be replaced with the related argument
        printf("<img src='%s'>",
            esc_url($imageURL));
    }
}

When using the "URL" Return Format, it's important to note that you cannot control the image size, and you won't have access to any additional information beyond the URL itself. Therefore, it's advisable to avoid this option and instead choose the "ID" Return Format for better flexibility and control.

For additional information, you can watch the video below and refer to the official ACF article.

ACF Gallery field with code, video cover

Final thoughts

#link copied

We've demonstrated how to use the ACF Gallery field, its various options, and two methods to display it. You should now be well-equipped to utilize this field effectively in your projects.

Remember that a View in the Advanced Views plugin supports all field types, and you can style the output by adding CSS rules within the View (utilize the CSS code field in the "Advanced" tab). What's advantageous about this approach is that the CSS is only loaded on pages where you've included the shortcode.

In the same "Advanced" tab, you can also incorporate JavaScript code, which is particularly useful for enhancing features like galleries. With the Basic version, you'll need to apply your custom CSS (and potentially JavaScript) to transform the default appearance into an interactive gallery. However, with the Pro version, the Masonry and Lightbox options are readily available without the need for coding.

We trust that you've found this article helpful. For more information about the Advanced Views plugin, please visit the official website.

About the Author
Maxim Akimov

Certified WordPress expert from Ukraine with over 8 years of experience. Advocate of the BEM methodology and the overall modular approach. Loves sporting activities and enjoys going to the gym and regularly plays table tennis.

0 Comments

    Leave a comment

    Reply to 

    Please be considerate when leaving a comment.

    Not shown publicly

    Got it