/** * The background image container class will be like this, when using the example CSS below: class="bg-image-ACF_FIELD_NAME". */function acf_multiple_responsive_background_images() { // Retrieve the ID for each ACF image field you have on the page and store in an array $acf_fields = get_field_objects(); // See https://www.advancedcustomfields.com/resources/get_field_objects/ for overview $acf_image_css = array(); // An empty array to hold generated CSS for output //var_dump( $acf_fields ); if ( $acf_fields ) { foreach ( $acf_fields as $field ) { // Loop through all of the ACF fields. if ( 'image' === $field['type'] ) { // Check if an image field. $banner_s = wp_get_attachment_image_src( $field['value'], 'banner-s' )[0]; $banner_l = wp_get_attachment_image_src( $field['value'], 'banner-l' )[0]; // The background image class includes the ACF field name to make it unique. $css = '.bg-image-' . $field['name'] . '{background-image:url(' . esc_url ( $banner_s ) . ');}@media(min-width: 75em){.bg-image-' . $field['name'] . '{background-image:url(' . esc_url( $banner_l ) . ');}}'; array_push( $acf_image_css, $css ); } } } $acf_image_css_string = implode( '', $acf_image_css ); // wp_add_inline_style() expects a string. // Set the CSS inline wp_add_inline_style( 'theme-css-handle', $acf_image_css_string );}add_action( 'wp_enqueue_scripts', 'acf_multiple_responsive_background_images' );
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.