Support

Account

Home Forums General Issues Assigning an Img Class in PHP

Helping

Assigning an Img Class in PHP

  • Hello,

    I’ve created a function that gets the image ID from ACF then creates a background that changes by the day of the week. I’d like to load the images by lazyload but don’t know how to assign an image class with the function. Grateful for any suggestions.

    function my_custom_background() {
    
    	if ( ! is_front_page() ) {
    		return;
    	}
    
    	$img_id = get_field( strtolower( date( 'l' ) ) );
    
    	echo "<style>\n";
    
    	// Large desktops.
    	
    	$img = wp_get_attachment_image_src( $img_id, 'large_desktop_background' );
    	
    
    	echo "body {\n";
    	echo sprintf( "\tbackground-image: url(%s);\n", $img[0] );
    	echo "}\n";
    	
    
    	// Small desktops.
    	
    	
    	$img = wp_get_attachment_image_src( $img_id, 'small_desktop_background' );
    	
    	
    	echo "@media (max-width: 1199px) {\n";
    	echo "\tbody {\n";
    	echo sprintf( "\t\tbackground-image: url(%s);\n", $img[0] );
    	echo "\t}\n";
    	echo "}\n";
    
    	// Tablets.
    	
    	$img = wp_get_attachment_image_src( $img_id, 'tablet_background' );
    	
    	
    	echo "@media (max-width: 991px) {\n";
    	echo "\tbody {\n";
    	echo sprintf( "\t\tbackground-image: url(%s);\n", $img[0] );
    	echo "\t}\n";
    	echo "}\n";
    
    	// Mobile.
    	
    	$img = wp_get_attachment_image_src( $img_id, 'phone_background' );
    
    	echo "@media (max-width: 767px) {\n";
    	echo "\tbody {\n";
    	echo sprintf( "\t\tbackground-image: url(%s);\n", $img[0] );
    	echo "\t}\n";
    	echo "}\n";
    
    	echo "</style>\n";
    
    }
    add_action( 'wp_head', 'my_custom_background' );
    
  • If you want to add a class to the body of the page then you need to use this hook https://developer.wordpress.org/reference/hooks/body_class/

Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Assigning an Img Class in PHP’ is closed to new replies.