
Hi,
I am trying to grab the first image from an acf image gallery field on a front end ACF Form and use that as the posts’ Featured Image.
I am using the ‘image array’ return format for the gallery and it is also located within a ‘group’ field.
If anyone can shed some light on my issue it would be most appreciated.
Here is my code in functions.php:
// Create a featured image from the first image in the gallery.
add_filter('acf/save_post', 'gallery_to_thumbnail');
function gallery_to_thumbnail($post_id) {
if ( have_rows( 'listing_media' ) ) :
while ( have_rows( 'listing_media' ) ) :
the_row();
$listing_image_gallery = get_sub_field( 'listing_image_gallery' );
if ( $listing_image_gallery) :
$gallery = get_sub_field( 'listing_image_gallery', false, false );
$image_id = $gallery[0];
set_post_thumbnail($post_id, $image_id);
endif;
endwhile;
endif;
}

I’m assuming from looking at your code that “listing_media” is the repeater.
if this is inside a group field then you also need to loop over the group field.
You also need to supply the post ID inside of the function for the first field.
if (have_rows('group_field_name', $post_id)) {
while (have_rows('group_field_name', $post_id)) {
the_row();
if (have_rows('listing_media')) {
while (have_rows('listing_media')) {
the_row();
$gallery = get_sub_field('listing_image_gallery', false, false);
// etc
}
}
}
}

Actually, the ‘listing_media’ is the group field. What resolved my issue was adding $post_id to the the end of ‘listing_media’.
if (have_rows('listing_media', $post_id)) {
while (have_rows('listing_media', $postId)) {
Thank you
You must be logged in to reply to this topic.
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.