Leave a Reply

1 comment

  1. I figured it out!

    1) The CMB “plugin” saves the attachment ID as as another meta key by adding “_id” to the end of it, so I used that to get the attachment ID, and
    2) I had variable scope issues. As soon as I called my global variable within my function, things started working. Here’s the final code:

    /**
     * Home Page Case Randomizer
     */
    
    $GLOBALS['_home_case_number'] = rand(1, 3);
    
    
    
    
    function home_case_number() {
        global $_home_case_number;
    
       if ( is_front_page() ) :  // checks whether this is the home page
    
    
        // get the attachment thumbnail ID
                $attachment_image = get_post_meta( get_the_ID(), '_home_case_background_' . $_home_case_number . '_id', true );
    
    
        // store the image sizes in an array
        $img_sizes = array( 'thumbnail', 'medium', 'large', 'full' );
    
        // grab the URL for each image size and store in a variable
        foreach ( $img_sizes as $img_size ) {
            ${ 'img_src_' . $img_size } = wp_get_attachment_image_src( $attachment_image, $img_size );
        }
    
    
    
        echo '<style type="text/css"> 
    
            .featured-image {
    
                width: 100%;        
                min-height:350px; 
                background-image: url(' . esc_url( $img_src_medium[0] ) . '); 
            }
    
    
            @media screen and ( min-width: 400px ) {
                .featured-image {
                    background-image: url(' . esc_url( $img_src_large[0] ) . ');
                }
            }
    
            @media screen and ( min-width: 1000px ) {
                .featured-image {
                    background-image: url(' . esc_url( $img_src_full[0] ) . ');
                }               
            }
    
    
        </style>';
    
        endif;
     };
    
    
    add_action( 'wp_head', 'home_case_number' );
    

    Hopefully this will help someone else out there.