Support

Account

Home Forums ACF PRO Featured Image from Gallery via ACF Form

Solved

Featured Image from Gallery via ACF Form

  • 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

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

You must be logged in to reply to this topic.

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 Cookie Policy. If you continue to use this site, you consent to our use of cookies.