I create the gallery meta box with ACF gallery field and uploading the images to my pages. At frontend I shall want one random image from those gallery images.
Here is the steps.
PHP Snippet
At first you would copy the following PHP code and paste into the Code Snippet plugin. Or you can use my Customize Oxygen Builder plugin and put the code inside the includes/helpers.php file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/** * Getting the random image URL from ACF gallery */ function paulc_get_random_image( $acf_field_key ) { if( ! function_exists( 'get_field' ) ) return; $getImages = get_field( $acf_field_key ); $size = 'full'; if( $getImages ) { $totalImages = count( $getImages ); $randomNumber = rand( 0, ( $totalImages - 1 ) ); if( $getImages[$randomNumber] ) return wp_get_attachment_image_url( $getImages[$randomNumber]['id'], $size ); } return; //* return a fallback image url } |
Dan says
Very good tutorial, helped me a lot for Oxygen. For Breakdance with MetaBox it would also be highly interesting.
Matt says
Hey Paul,
Thanks for this tutorial,
Is there a way to edit the above code for MetaBox.io? I tried the below snippet but no results. Can you please suggest a solution:
function paulc_get_random_image( $field_id ) {
if( ! function_exists( ‘rwmb_get_value’ ) )
return;
$images = rwmb_get_value( $field_id );
$size = ‘full’;
if ( ( $images ) ) {
$total_images = count( $images );
$random_number = rand( 0, ( $total_images – 1 ) );
if ( $images[$random_number] ) {
return wp_get_attachment_image_url( $images[$random_number][‘ID’], $size );
}
}
return; //* return a fallback image URL
}
Thanks
Paul says
Hi Matt,
Can you try this code?
naza says
Hy, thanks for the tutorial. How can I make this in elementor