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.
The topic ‘Get gallery from post object’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.