Skip to content

Instantly share code, notes, and snippets.

@HongPong
Created August 27, 2019 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HongPong/8f33357439ac9370065bfbdbad8e3d74 to your computer and use it in GitHub Desktop.
Save HongPong/8f33357439ac9370065bfbdbad8e3d74 to your computer and use it in GitHub Desktop.
ACF responsive background image method
https://acfextras.com/responsive-background-image-acf/
function biscuit_responsive_hero_image_css(){
$image = get_field( 'hero_page_image' );
// Get the Image from ACF, then set a big and small version of it from predefined custom image sizes
$big_image_output = wp_get_attachment_image_url( $image, 'hero-slide'); // Use ACF Image ID not Array or URL
$small_image_output = wp_get_attachment_image_url( $image, 'mpu-medium');
// Add it to a custom CSS file that is already being enqueued. The handle ('hero-image-css' in this case), must match below and in the enqueue_style line.
$custom_css = "
/* Mobiles */
.hero-image-bg{
background-image:url('{$small_image_output}');
}
/* Desktop */
@media screen and (min-width: 768px) {
.hero-image-bg{
background-image:url('{$big_image_output}');
}
} ";
wp_add_inline_style( 'hero-image-css', $custom_css );
}
add_action( 'wp_enqueue_scripts', 'biscuit_responsive_hero_image_css' ,30);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment