Support

Account

Home Forums Gutenberg Set featured image from acf image field from ACF block

Helping

Set featured image from acf image field from ACF block

  • I created an ACF block which has an image field.
    The field is registered with php like this and it is working fine:

    		[
    			'key' => 'field_cpt_case_header_img',
    			'name' => 'cpt_case_header_img',
    			'label' => esc_html__( 'Representetive image', 'wptheme' ),
    			'type' => 'image',
    			'required' => '1',
    			'preview_image' => 'thumbnail',
    		],

    And I have this function to save the image field as featured image:

    function case_set_featured_image( $post_id ) {
    	if ( get_post_type( $post_id ) !== 'case' ) {
    		return;
    	}
    
    	$acf_image = get_field( 'cpt_case_header_img', $post_id );
    
    	if ( $acf_image ) {
    		// Attempt to set ACF image as the featured image
    		$result = update_post_meta( $post_id, '_thumbnail_id', $acf_image['ID'] );
    		$featured_image_id = get_post_thumbnail_id( $post_id );
    	}
    }
    add_action( 'save_post', 'case_set_featured_image' );

    But no featured image is saved, it is empty.

  • I have this on another site not using ablock editor and works just fine:

    function acf_set_featured_image( $value, $post_id, $field ) {
    	if ( '' !== $value ) {
    		//Add the value which is the image ID to the _thumbnail_id meta data for the current post
    		update_post_meta( $post_id, '_thumbnail_id', $value );
    	}
    	return $value;
    }
    add_filter( 'acf/update_value/name=hero_image_slideshow_single_image', 'acf_set_featured_image', 10, 3 );
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.