Support

Account

Home Forums Add-ons Gallery Field Feature image from first gallery image

Solving

Feature image from first gallery image

  • I know this has been covered before, but I am having an unexpected problem. I want the featured image to take the first image of the gallery – it does this with the code below, but only after I Update the post within Admin – the featured post is not set when the post is initially published…Any ideas?

    
    function set_featured_from_gallery() {
    	
        global $post;
        $post_id = $post->ID;
    
        $has_thumbnail = get_the_post_thumbnail($post_id);
    
          if ( !$has_thumbnail ) {
    
            $images = get_field('images', $post_id, false);
            $image_id = $images[0];
    
            if ( $image_id ) {
              set_post_thumbnail( $post_id, $image_id );
            }
          }
    
    }
    add_action( 'save_post_galleries', 'set_featured_from_gallery', 10, 3 );
    
  • "save_post_{$post_type}" runs before "save_post". ACF does not set the values of the field until the second hook. So you are trying to get values from a field that has not been set yet. When you update the post the second time (and after) you are using values that were saved the previous time the the post was saved and it will not reflect changes correctly if the first image in the gallery has been changed.

    Whenever dealing with ACF you need to use the acf/save_post hook. https://www.advancedcustomfields.com/resources/acf-save_post/

    I know that you are trying to limit your filter to a specific post type, but you can do this in your acf/save_post filter

    
    add_action( 'acf/save_post', 'set_featured_from_gallery', 20);
    set_featured_from_gallery ($post_id) {
      if (get_post_type($post_id) != 'galleries') {
        return;
      }
      // code continues...
    }
    
  • Thanks John,

    I made the changes you suggested.

    Not sure if the changes were just recommendations, or for getting the feature image set the first time around.

    In any case, nothing really has changed.

    Is there a way to get the feature image set the first time around?

    Can I writer another function or something to force the trigger?

    Thanks
    Patrick

  • This reply has been marked as private.
  • I just created a gallery field simply named “gallery” and added this simple function

    
    add_filter('acf/save_post', 'gallery_to_thumbnail');
    function gallery_to_thumbnail($post_id) {
    	$gallery = get_field('gallery', $post_id, false);
    	if (!empty($gallery)) {
    		$image_id = $gallery[0];
    		set_post_thumbnail($post_id, $image_id);
    	}
    }
    

    This works, the first image in the gallery is set as the featured image when I save as a draft or I when I publish.

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

You must be logged in to reply to this topic.