Support

Account

Home Forums ACF PRO Get gallery from post object

Solved

Get gallery from post object

  • I have a custom post type and each post just has a title and an acf gallery with multiple images. In the admin area on my pages I have assigned a post object “gallery_select” to pull through a list of the galleries (field name “gallery”) belonging to the custom post type. I want to be able to select one gallery and assign it to the page, but am not having much success.

    function show_page_gallery() {	
    $post_objects = get_field('gallery_select');
    if( $post_objects ):
    	foreach( $post_objects as $post_object):
    		$images = get_field('gallery',$post_object->ID);
    		if( $images ):
    			foreach( $images as $image ):
    				echo '<img src="'.$image['url'].'" />';
    			endforeach;
    		endif;
    	endforeach;
    endif;
    }
  • Hi @redsun

    Did you call the post object field outside The Loop? If you did, you need to set the post ID for the second parameter like this:

    global $post;
    $post_objects = get_field('gallery_select', $post->ID);

    Also, please make sure that you used a multiple post objects field. If you used a single post object field, you don’t have to loop through the $post_objects variable.

    If you still can’t solve the issue, could you please share the JSON or XML export file of your field group?

    Thanks!

  • Hi @james

    Thank you so much – I’m calling this from functions.php so it’s outside the loop. I only need one gallery so didn’t need the foreach wrapped round the $post_objects variable (and so changed $post_object->ID to $post_objects->ID for the ‘gallery’ field.

    function show_page_gallery() {
    global $post;
    $post_objects = get_field('gallery_select',$post->ID);
    if( $post_objects ):
    	$images = get_field('gallery',$post_objects->ID);
    	if( $images ):
    		foreach( $images as $image ):
    			echo '<img src="'.$image['url'].'" />';
    		endforeach;
    	endif;
    endif;
    }

    The example above is much simplified but works. I’ve now added back all the HTML required to wrap and style the gallery images and it’s displaying perfectly.

    Thanks again.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.