Matt Radford

Messing with links since <blink>

ACF – Saving the first gallery image as the featured image

Published on 

I decided to use the Advanced Custom Fields Gallery field to show some images on a specific post type. Easy enough, but I wanted to set the featured image from the first gallery image, as there’s a performance hit involved in retrieving all those gallery arrays on, say an archive or search results page. A quick Googling and I found some code that almost did it:

http://support.advancedcustomfields.com/forums/topic/display-1-gallery-picture-on-archive-page/

The answer from marius.stuparu almost did do the job, namely:

function set_featured_image_from_gallery() {
$has_thumbnail = get_the_post_thumbnail($post->ID);
if ( !$has_thumbnail ) {
$images = get_field('gallery', false, false);
$image_id = $images[0];
if ( $image_id ) {
set_post_thumbnail( $post->ID, $image_id );
}
}
}
add_action( 'save_post', 'set_featured_image_from_gallery' );

However, I noticed straight away a couple of problems. I’m using this in a functions.php file, i.e. outside the loop, so global $post was required, plus some changes to get_field.

But more than that, the code was giving a load of trying to get property of non-object errors when saving other post objects in the backend, such as menus. The solution was changing the hook from save_post to save_post_{$post-type}, which is documented in the Codex entry for save_post; its been there since 3.7.

So the solution then, which doesn’t give any errors, is below.