
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.
/**
* 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
}
This is a great tutorial. Is there anyway to have a stylized caption with this? I think I found a solution through some folder plugins and Hot Random Image, but styling the caption has been difficult for me to figure out.
Very good tutorial, helped me a lot for Oxygen. For Breakdance with MetaBox it would also be highly interesting.
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
Hi Matt,
Can you try this code?
function paulc_get_random_image( $field_id ) { if( ! function_exists( 'rwmb_get_value' ) ) return; $images = get_post_meta( get_the_ID(), $field_id, false ); $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], $size ); } } return; //* return a fallback image URL }Hy, thanks for the tutorial. How can I make this in elementor