set_post_thumbnail saves the thumbnail twice, how to set it once

Question

I have a code that gets an external image from a YouTube url and stores it as a thumbnail. When I save the post, it saves the image twice. How do you prevent saving an image more than once?

Here’s my code:

function post_extra_save( $post_id, $post){
if ( has_blocks( $post->post_content ) ) {
    $blocks = parse_blocks( $post->post_content );
    foreach ( $blocks as $block ) {
        if ( $block['blockName'] === 'acf/opby-video' ) {
            // get the url from a text field in a block
            $media_video_url = explode('/', $block['attrs']['data']['youtube_url']);
            // if youtube is selected
            if ($block['attrs']['data']['video_provider'] == 'youtube') {
                // get the url for external image
                $yt_url_raw = str_replace("watch?v=","",$media_video_url[3]);
                $thumbnail = 'http://img.youtube.com/vi/' . $yt_url_raw . '/maxresdefault.jpg';
                // side load the image and save the url as a thunbnail
                $vidimage = media_sideload_image( $thumbnail, $post->ID, $filename, 'id' );
                set_post_thumbnail($post->ID, $vidimage);
            }
        }
    }
};

}
add_action( ‘save_post’, ‘post_extra_save’, 10, 2 );

0
Gregory Schultz 6 months 2020-12-16T23:10:22-05:00 0 Answers 2 views 0

Leave an answer

Browse
Browse