Oaky I have question with having dynamic background images that are also responsive.
So what I have done is for a home page, I created a custom image uploader for the main header image so the user can change it for that page. But I want to load the image size based on the screen size with css media queries.
I then created a herostyle.php file and added the following code:
<?php
$absolute_path = explode('wp-content', $_SERVER['SCRIPT_FILENAME']);
$wp_load = $absolute_path[0] . 'wp-load.php';
require_once($wp_load);
header("Content-type: text/css; charset: UTF-8");
$heroImage = get_post_meta( 6, 'main_header_image', true );
$heroImageFull = wp_get_attachment_image_src( $heroImage, 'herofull' );
$heroImageDesk = wp_get_attachment_image_src( $heroImage, 'herodesk' );
$heroImageTab = wp_get_attachment_image_src( $heroImage, 'herotab' );
$heroImageMobile = wp_get_attachment_image_src( $heroImage, 'heromobile' );
?>
.home-hero {
height: 500px;
background-image: url(<?php echo $heroImageMobile[0]; ?>);
}
@media screen and (min-width: 768px) {
.swb-hero {
background-image: url(<?php echo $heroImageTab[0]; ?>);
}
}
@media screen and (min-width: 1024px) {
.swb-hero {
background-image: url(<?php echo $heroImageDesk[0]; ?>);
}
}
@media screen and (min-width: 1600px) {
.swb-hero {
background-image: url(<?php echo $heroImageFull[0]; ?>);
}
}
I then added this stylesheet within my functions.php file with the following code:
function my_new_styles() {
wp_enqueue_style( 'hero', get_template_directory_uri() . '/src/sass/herostyle.php', null, null );
}
add_action( 'wp_enqueue_scripts', 'my_new_styles' );
So what I am doing is the uploaded image is 2400px wide, then I create the four responsive images with WordPress using the following code in my functions.php:
add_image_size( 'herofull', 2400, 4000, false);
add_image_size( 'herodesk', 1600, 4000, false);
add_image_size( 'herotab', 1000, 4000, false);
add_image_size( 'heromobile', 800, 4000, false);
So I guess my question would be, is this good practice just to have the ability for a user to change and an image for backgrounds. I want it to be responsive as well. I would hate to serve a 2400px wide image to a mobile device. If I do this with CSS, then it is not changeable by the user, and I do not want to use inline CSS with PHP for this.
Does anybody know if this has any benefits? Are there better solutions to this issue? The one thing I don't like about this is added another style sheet to the website, should I care?
Thanks for any help/advice on this issue!