Site logo

Archived topic

Displaying ACF Array Field using shortcode in GenerateBlocks

3 replies · Started by Aldrin on August 4, 2022

Viewing posts 1–4 of 4

Hi there, I am trying to display the list of image urls on the frontend via a shortcode
I created in function.php. I used this shortcode in a Post Layout I created in GenerateBlocks. I used an ACF Custom Field which is a Gallery Field Type called
vehicle_gallery_images so have to fetch the values via foreach since its an array. Mostly works fine but the urls echo above all content and not where I placed the shortcode. I tried return implode($images); way listed below and that displays the urls where I place the shortcode but I'm limited in wrapping the urls with html element.

I am aware of the below post reply by David, but wanted to see if there is a work around.

https://generatepress.com/forums/topic/gb-query-loop-display-acf-datas-via-shortcode/#post-2303182
Loop Method:

function getImages(){
 
 $images = get_field('vehicle_gallery_images'); 
     if ($images){   
    foreach($images as $image){
        echo $image;
    } 
     } else {         
         return '';
     }
  
}

add_shortcode('vehicle_image_gallery','getImages');

Implode Method:

function getImages(){
 
 $images = get_field('vehicle_gallery_images'); 
 
 if($images)  {
  
    return implode($images);
     
 } else {
     
     return 'none';
 }
      
}

add_shortcode('vehicle_image_gallery','getImages');

Managed to use hooks instead without creating a shortcode. Better actually. Created a Hook Element and chose a placement and included the below php.

// Get URL Array from ACF Field vehicle_gallery_images
$image_urls = get_field('vehicle_gallery_images'); 
if ($image_urls){   
    foreach($image_urls as $image_url){
        echo '<div><a href="'.$image_url.'"><img src="'. $image_url . '"/></a></div>';
    } 
     } else {         
         return '';
     }

Hi Aldrin,

Glad you figured it out! Thank you for sharing!

Anytime, thanks

This archived topic is closed to new replies.