13th Feb '24
/
0 comments

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 633 Bricks code tutorials with BricksLabs Pro

Leave the first comment

 

Related Tutorials..

Pro
Dynamic Source for Video Element in Bricks Using Meta Box Post Field

Dynamic Source for Video Element in Bricks Using Meta Box Post Field

This Pro tutorial provides the steps to set the source of a Bricks video element on single CPT pages to be the URL of a…
Categories:
Pro
Conditional Rendering Based on Current Date and Time in Bricks when Using Meta Box

Conditional Rendering Based on Current Date and Time in Bricks when Using Meta Box

A Pro member of our site asks: Using bricks + Meta, conditionally show a post listing under 3 different conditions, based on the Current Date…
Pro
Meta Box Relationship Posts Filtered by a Taxonomy Term in Bricks

Meta Box Relationship Posts Filtered by a Taxonomy Term in Bricks

Updated on 17 Feb 2025 In the Inner Circle a user asks: Hello, I have a relationship made in metabox between two Post Types “Travel”…
Categories:
Pro
Bricks Forms + Meta Box: Auto-Create Post Relationships on Form Submission

Bricks Forms + Meta Box: Auto-Create Post Relationships on Form Submission

How to link a Bricks post-creation form on a post to a newly created post of another post type using Meta Box relationship.
Pro
Sort Posts by Meta Box Group Sub Field in Bricks

Sort Posts by Meta Box Group Sub Field in Bricks

This Pro tutorial provides the steps to order posts in Bricks by the value of a Number-type of sub field that is inside a Meta…