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

Leave the first comment

 

Related Tutorials..

Pro
Dynamic Post-specific Templates in Bricks using Meta Box/ACF Select Field

Dynamic Post-specific Templates in Bricks using Meta Box/ACF Select Field

Update on 23 Aug 2023: Added steps for ACF. Bricks builder v1.8.4 introduced an pretty useful filter called bricks/active_templates that flew under the radar. This…
Pro
Filtering Query Loop Posts by a Non-empty Custom Field in Bricks

Filtering Query Loop Posts by a Non-empty Custom Field in Bricks

This Pro tutorial shows how we can prefilter the results of a query output by a Bricks query loop to only those for which the…
Categories:
Tags:
Pro
Meta Box Checkbox List Query Type in Bricks

Meta Box Checkbox List Query Type in Bricks

This Pro tutorial provides the steps to add a new query type in Bricks builder for displaying the values of a Checkbox List type of…
Categories:
Pro
Bricks Dynamic Condition – Check if today falls within 5 days before any holiday date

Bricks Dynamic Condition – Check if today falls within 5 days before any holiday date

Creating a custom condition that returns true or false depending on whether today falls within 5 days before any holiday dates selected on a Meta…
Categories:
Tags:
Pro
Post Data for the Current User in Bricks with Meta Box

Post Data for the Current User in Bricks with Meta Box

How to configure a query loop to output the post data of the SalesRep CPT associated with the current user.
Categories:
Pro
Meta Box Date Field Value Custom Format in Bricks

Meta Box Date Field Value Custom Format in Bricks

Updated on 3 Apr 2024 Note: A custom function is no longer needed. Use the date format filter, as mentioned in the Bricks documentation. Ex.:…
Categories:
Tags: