Dynamically populating Blockstudio Slider with ACF Gallery

tdrayson

A member of The Admin Bar, was looking for a way to dynamically show images from a custom post type with an ACF Gallery, inside a slider.

Demo

Blockstudio have their own small library of blocks that you can use, one of which includes a slider block.

Normally, this block requires you to manually select static images to display in the slider. However with a handy little hook that Blockstudio provides, we can use this to tell the block to load from our own source, rather than the static images.

1. Enable Blockstudio Library

To enable the Blockstudio library, we need to add following code into functions.php or code snippet plugin.


        add_filter("blockstudio/library", "__return_true");
      
Copy

We need to create an ACF gallery field and assign it to our post type.

Make sure you set the Return format to Image URL.

screenshot 2023 02 14 at 00.28.29

Next we need to create a post and add some images to our newly created ACF gallery.

screenshot 2023 02 14 at 00.30.06

4. Creating our template

I am using GeneratePress’ Elements feature to create my single post template that I will add the slider to.

Find the Blockstudio Slider block from the block menu and insert it into your template.

You can configure your slider settings on right sidebar.

Add the class dynamic-slider to the block under the advanced settings.

Don't add any images from the media library here, we are going to dynamically populate this later on.
screenshot 2023 02 14 at 00.32.36

5. Add the render function

Now is time to dynamically populate our gallery. To do this, we are going to use the blockstudio/blocks/attributes/render hook.

Make sure line 6 and line 9 both match their respective class and field name that we set earlier.


        add_filter("blockstudio/blocks/attributes/render", function ($value, $key, $block) {
    if (
        $key === "images" &&
        $block["name"] === "blockstudio-element/slider" &&
        // class to target specific slider
        $block["className"] === "dynamic-slider"
    ) {
        // replace 'gallery' with field name
        $gallery = get_field("gallery"); 

        if (!$gallery) return;
        
        foreach ($gallery as $image) {
            $value[] = ["url" => $image];
        }
    }

    return $value;
},10,3);
      
Copy

6. Final output

You should now be able to visit your blog post, and the slider should have populated with the images you selected in the ACF gallery.

screenshot 2023 02 14 at 00.42.10

👋🏻 Weekly Tutorial Digest

I send out a weekly newsletter with links to new tutorials written in the last week, you can subscribe below.

Newsletter

🔒I won't send you spam, I promise