Random Meta Box Image

Looking to output a random image from a set of images upload to a post via a Meta Box Images Advanced-type field in Bricks?

Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:

<?php 

function bl_get_random_mb_image_advanced_image_id( string $field_id ): int {
    $images = rwmb_meta( $field_id );

    shuffle( $images );

    return reset( $images )['ID'];
}

In the Bricks template that applies to your post or for all posts of your post type, add an Image element and set its source to:

{echo:bl_get_random_mb_image_advanced_image_id(random_image)}

Replace random_image with your field ID.

To attach a field group to your site’s homepage:

where “Home” is the static Page set as site’s homepage at Settings → Reading.

Get access to all 526 Bricks code tutorials with BricksLabs Pro

Leave the first comment

 

Related Tutorials..

Pro
Post Data for the Current User in Bricks with Meta Box

Post Data for the Current User in Bricks with Meta Box

In the Bricks Facebook group a user asked: I need help with Metabox and Bricks! I have created a CPT "SalesRep" with multiple custom fields…
Categories:
Pro
Meta Box/ACF Images Staggered Grid Gallery in Bricks

Meta Box/ACF Images Staggered Grid Gallery in Bricks

Showing images from two Gallery-type of ACF or Image Advanced-type of Meta Box fields in a staggered grid layout.
Pro
Meta Box Group Subfield Text’s Slug as Query Loop Item ID in Bricks

Meta Box Group Subfield Text’s Slug as Query Loop Item ID in Bricks

In the BricksLabs Facebook group a user asks: I have a metaBox custom field called 'section_title' inside a clonable metabox group called 'about_section' How can…
Categories:
Tags: