Change background image based on tags

I’ve actually fixed a solution, this solution uses a custom field in the post, and based on that, loads a background to the post.

To get ride of the issue with different formats on the background image, I got help from (don’t remember the name) to write a code where it first tries to load background.jpg, and if that fail, it will load background.gif and so on.
So by adding this code to functions.php, will do the trick

// set background based on custom field in post
    function rbpet_post_background () {

        if ( empty( $background = get_post_meta( get_the_ID(), 'usp-custom-background_image', true ) ) ) return;
        $base = "https://example.com/img/backgrounds/";
        $extensions = array( ".jpg" , ".gif" , ".mp4" );

        foreach ( $extensions as $ext ) {

            $file = $base . $background . $ext;
            $file_headers = @get_headers( $file );
            if ( $file_headers[0] == "HTTP/1.1 200 OK" ) {
                $background_url = $file;
                break;
            }

        }

       if ( empty( $background_url ) ) return;
    ?>
        <style type="text/css">
                body { background-image: url( "<?php echo ($background_url); ?>")!important; 
    background-size: cover; 
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: center center;
    max-width: 100%;
    height: auto;

    }
            </style>
    <?php
    }

    add_action( "wp_head" , "rbpet_post_background" );