Tuesday, September 27, 2022
The Great Tit
Updated: 30. 9. 2022, Added: 27. 9. 2022

Use first ACF Gallery image as Featured image of Custom post type single

How do I set the first gallery image from a custom post type gallery field as the featured image? Found this here: Use first image from gallery of custom post type to set featured image - ACF Support (advancedcustomfields.com)

It use ACF | acf/save_post (advancedcustomfields.com) filter to apply.

add_action('acf/save_post', 'flex_FeaturedImageSetByACF', 50);

function flex_FeaturedImageSetByACF() {

    $current_screen         = get_current_screen(); // Current admin screen needed to identify the current cpt
    $current_cpt_name       = 'models'; // Current cpt name
    $current_cpt_support    = 'thumbnail'; // We want to check if the CPT supports this feature

    global $post;

    $post_id                = ( $post->ID ); // Current post ID
    $post_gallery_field     = get_field('model_gallery', $post_id ); // ACF field

    if  ( !empty( $post_id ) ) {

        if ( isset( $post_gallery_field['0'] ) ) {

            $post_image_id          = $post_gallery_field['0']['id']; // ACF image filed ID
            $post_image_url         = $post_gallery_field['0']['url']; // ACF image filed URL

            // If current cpt supports thumbnails/featured images

            if ( post_type_supports( $current_cpt_name, $current_cpt_support ) ) {

                if ( ( $post_image_url ) AND ( ( $post_image_url ) != ( get_the_post_thumbnail() ) ) ) {

                    update_post_meta($post_id, '_thumbnail_id', $post_image_id);

                }

            }

        } else {

            update_post_meta( $post_id, '_thumbnail_id', 0 );

        }

    }

}
Did I help you? Support me on Patreon!
Beep this article to your friends!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram