Support

Account

Home Forums General Issues Using first gallery image as the featured image…

Solving

Using first gallery image as the featured image…

  • I am using the following code to make it so that the first image in the gallery field is selected as the featured image for that post:

    //make first gallery image featured image
    
    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 when I publish in admin, but when a user creates a new post on the front end, the featured image is not set.

  • I’ve just noticed it works when I update only.

  • Using PHP will only work when you click the update button and will not assign the image to the featured image when you do so. I would call this working as expected.

    If you want to have the first gallery image automatically populate in the featured image before updating the post then you’ll need to build custom JavaScript to do this. https://www.advancedcustomfields.com/resources/adding-custom-javascript-fields/

  • Thanks for your reply John.

    I managed to make this work with the following code:

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

    I realised my issue isn’t with setting the featured image but setting the og:image based on the featured image for which I am using Yoast plugin. This only works once I update a post rather than create one.

    I know Yoast has a filter but I am unsure how to set it using the gallery field, any ideas would be greatly appreciated:

    add_filter('wpseo_opengraph_image', 'og_image');
     
    function og_image($image) {
        global $post;
     
        if (get_field('feature_image', $post->ID)) {
            $image = base_image_url(get_field('feature_image', $post->ID), null); 
        }
        return $image;
    }
Viewing 5 posts - 1 through 5 (of 5 total)

The topic ‘Using first gallery image as the featured image…’ is closed to new replies.