Generate / attach Image srcsets from ACF Image Field

Question

I currently have an ACF save post action that takes an image and assigns it to be the featured image. One problem I am having is displaying the srcsets.

<img
     src="<?php echo esc_url( $img_src ); ?>"
     
     alt="<?php echo $image['alt']; ?>" title="<?php echo $image['alt']; ?>"
                            />
 add_action('acf/save_post', 'my_acf_save_post_image');
 function my_acf_save_post_image( $post_id ) {

    $posttype = get_post_type($post_id);
    $wistia_image_url = get_field('image', $post_id);
    $wistia_video_url = get_field('wistia', false, false);      

    if (($posttype == 'post' && !empty($wistia_image_url)) && empty($wistia_video_url) ) {
        $img_src = wp_get_attachment_image_url( $wistia_image_url['id'], 'mobile-large' );      

        // Define attachment metadata
        $attach_data = wp_generate_attachment_metadata( $wistia_image_url['id'], $img_src );

        // Assign metadata to attachment
        wp_update_attachment_metadata( $wistia_image_url['id'], $attach_data );

        #Not working. First parameter has to be the actual image file from what I've read?
        wp_image_add_srcset_and_sizes($wistia_image_url, $attach_data,  $wistia_image_url['id']);

        // And finally assign featured image to post
        set_post_thumbnail( $post_id, $wistia_image_url['id'] );
    }
 }

I understand that the get_field of an image element will return sizes that has all the sizes, but individually. Is there a way to assign those sizes into the srcset of an attachment so when I use wp_get_attachment_image_srcset, it would pull the srcset in one go rather than setting them all individually?

0
xaykogeki 1 month 2023-02-15T23:58:33-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse