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
Filtering posts by a group field’s true / false field sub field value with ACF or Meta Box in Bricks

Filtering posts by a group field’s true / false field sub field value with ACF or Meta Box in Bricks

This Pro tutorial covers how posts of a Bricks query loop can be filtered to show only the ones whose true / false or checkbox…
Categories:
Tags:
Pro
Nested Meta Box Query Loop Inside a CPT Query Loop in Bricks

Nested Meta Box Query Loop Inside a CPT Query Loop in Bricks

This Pro tutorial provides the steps for setting up a cloneable Meta Box group query inside a CPT query in Bricks. Scenario: CPT: course Meta…
Categories:
Pro
Filtering posts by a group field’s subfield value with Meta Box when using a custom table in Bricks

Filtering posts by a group field’s subfield value with Meta Box when using a custom table in Bricks

Filtering a query loop to output only those posts with the value of a Select subfield of a Group field set to Yes when using…
Categories:
Tags:
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:
Color Custom Field as Section Background Color on Category/Term Archives in Bricks

Color Custom Field as Section Background Color on Category/Term Archives in Bricks

How to use a color from a taxonomy term custom field for as the hero section background color on archive pages.
Categories:
Tags:
Pro
MB Favorite Posts in Bricks

MB Favorite Posts in Bricks

This tutorial explores using MB Favorite Posts in Bricks, including outputting the list of favorites via a query loop.
Categories:
Filtering Bricks Posts Query Loop by Meta Box Group’s Radio Subfield Value

Filtering Bricks Posts Query Loop by Meta Box Group’s Radio Subfield Value

In the past we showed how a Bricks posts query loop can be filtered by Meta Box group's subfield of types text/number and Datepicker here.…
Categories: