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.

Instant access to 390+ Bricks code tutorials with BricksLabs Pro

Leave the first comment