Skip to content

Instantly share code, notes, and snippets.

@gaelbillon
Last active September 27, 2021 11:52
Show Gist options
  • Save gaelbillon/58d2e917a83053ed5dc739d8ee538802 to your computer and use it in GitHub Desktop.
Save gaelbillon/58d2e917a83053ed5dc739d8ee538802 to your computer and use it in GitHub Desktop.
Wordpress / ACF : Set gallery image from featured image. If featured image is set and gallery field is empty.
add_action( 'save_post', 'set_first_gallery_image_from_featured_image' );
function set_first_gallery_image_from_featured_image() {
$post = get_post();
$featured_image = get_the_post_thumbnail($post->ID);
$acf_gallery = get_field('images', false, false); // Change images to the name of the ACF gallery field you want to update
$attachments_ids = [ 0 => get_post_thumbnail_id($post->ID) ];
if ( $featured_image && !$acf_gallery ) {
update_field('images', get_post_thumbnail_id($post->ID), $post->ID);
//delete_post_thumbnail($post->ID); // Uncomment to also delete the post thumbnail
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment