Ask your WordPress questions! Pay money and get answers fast! (more info)

Replace Image size related to screen resolution?

  • SOLVED

I am currently displaying large size images on single.php. I would like a solution where I can serve other image sizes for smaller screen sizes.

So for instance the standard setup currently displays the post images in large size at 1130px. However if someone was to access the post on a phone with a resolution of 480px then the site would serve the medium version of the image.

I am looking for an active solution and help, please don't just send me links to adaptive images or picture fill etc.

I am hoping that it is possible to do this within wordpress with some code to detect the browser resolution and then swap image size on the fly. No plugins please.

Answers (6)

2014-04-14

Sébastien | French WordpressDesigner answers:

I know that is a link but it's the perfect solution :)
[[LINK href="http://premium.wpmudev.org/blog/diy-truly-responsive-images-on-your-wordpress-website/"]]http://premium.wpmudev.org/blog/diy-truly-responsive-images-on-your-wordpress-website/[[/LINK]]
With this solution, to insert an image you use a shortcode like that :
[rimg src="http://link-to-full.size/image.png caption="This will be the alt and caption"]
and WordPress will be able to know the resolution of the screen and serve the best image for this resolution (the smaller image)

Instead of the solution of Dbranes, you use just one shortcode for one image, not one shortcode for one image in one resolution.


julesphoto comments:

Is it possible to do it without shortcode?


Sébastien | French WordpressDesigner comments:

we can probably imagine the same system, searching in all content the tag <img> with a regex.


julesphoto comments:

I am only thinking that if you have to insert shortcodes everywhere and then in the future I change the system I need to go and remove or update them all the posts.

Is it possible to expand upon this to also check browser resolution and then serve the correct attachment size?


<?php
$images =& get_children( array (
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'image'
));

if ( empty($images) ) {
// no attachments here
} else {
foreach ( $images as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, 'thumbnail' );
}
}
?>



Sébastien | French WordpressDesigner comments:

This method (see my link) check browser resolution and then serve the correct attachment size...
If you don't want to use shortcode you can probably adapt this code with a system of regex instead of shortcode.


If you want adapt your function, why do not just use mobble (here : http://wordpress.org/plugins/mobble/)
With this little plugin you can use different conditionnal tag like : is_iphone(), is_mobile() and is_tablet().

For example, you code became :
<?php

$images =& get_children( array (
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'image'
));


if ( empty($images) ) {
// no attachments here
} else {
foreach ( $images as $attachment_id => $attachment ) {
if (is_mobile()) echo wp_get_attachment_image( $attachment_id, 'small' );
elseif (is_tablet()) echo wp_get_attachment_image( $attachment_id, 'medium' );
else echo wp_get_attachment_image( $attachment_id, 'large' );
}
}

?>



julesphoto comments:

This is exactly what I want but is it not possible to define resolutions instead? So where it says is_mobile I can set a screen detection script? This way I can avoid the plugin.


Sébastien | French WordpressDesigner comments:

You can add this function in your file functions.php

add_filter('get_image_tag', 'restructure_imgs', 10, 2);
function restructure_imgs($html, $id, $alt, $align, $size='thumbnail') {

$sizes= array('thumbnail', 'medium', 'large', 'full');

$pic_mobile = wp_get_attachment_image_src($id, 'thumbnail');
$pic_tablet = wp_get_attachment_image_src($id, 'medium');
$pic_desktop = wp_get_attachment_image_src($id, 'large');


list( $img_src, $width, $height ) = image_downsize($id, $size);
$hwstring = image_hwstring($width, $height);

$title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';

$class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
$class = apply_filters('get_image_tag_class', $class, $id, $align, $size);

$html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title;
$html.= 'data-img-tablet-url="'.$pic_tablet[0].'" data-img-tablet-width="'.$pic_tablet[1].'" data-img-tablet-height="'.$pic_tablet[2].'"';
$html.= 'data-img-desktop-url="'.$pic_desktop[0].'" data-img-desktop-width="'.$pic_desktop[1].'" data-img-desktop-height="'.$pic_desktop[2].'"';
$html.= 'data-img-mobile-url="'.$pic_mobile[0].'" data-img-mobile-width="'.$pic_mobile[1].'" data-img-mobile-height="'.$pic_mobile[2].'"';
$html.= '>';
//$html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );

return $html;
}


All images that you will insert will be like something like that :

<img src="http://your-site/wp-content/uploads/2014/04/example-image-150x150.jpg" alt=""
data-img-tablet-url="http://your-site/wp-content/uploads/2014/04/example-image-300x195.jpg"
data-img-tablet-width="300"
data-img-tablet-height="195"
data-img-desktop-url="http://your-site/wp-content/uploads/2014/04/example-image.jpg"
data-img-desktop-width="960"
data-img-desktop-height="624"
data-img-mobile-url="http://your-site/wp-content/uploads/2014/04/example-image-150x150.jpg"
data-img-mobile-width="150"
data-img-mobile-height="150"
>


Now you can add jQuery and this script :

jQuery(document).ready(function($){
/* This function choose the good image relating resolution */
/* by Sébastien|french WordPressDesigner */
/* http://www.wpquestions.com/user/profile/id/2608 */

function checkWidth() {

if("matchMedia" in window) { // Détection du matchmedia
if(window.matchMedia("(min-width:1000px)").matches) {
console.log('min-width:1000px');
$("img[data-img-desktop-url]").each(function(i){
this.src = $(this).data("img-desktop-url");
});
}
else if(window.matchMedia("(min-width:800px)").matches) {
console.log('min-width:800px');

$("img[data-img-tablet-url]").each(function(i){
this.src = $(this).data("img-tablet-url");
});

}
else if(window.matchMedia("(min-width:400px)").matches) {
console.log('min-width:400px');
$("img[data-img-mobile-url]").each(function(i){
this.src = $(this).data("img-mobile-url");
});
}
}
}

// au chargement
checkWidth();
// au resize
$(window).on('resize',function(){
checkWidth();
});

});


Here the size of the image (thumbnail, medium or large) will be choice relating the media-query (min-width:400px,min-width:800px or min-width:1000px)


Sébastien | French WordpressDesigner comments:

Have you try this code ?


julesphoto comments:

hi, not yet. hope to try it today.

2014-04-14

Hariprasad answers:

You can try like this


if ( has_post_thumbnail() ) {
if ( wp_is_mobile() ) {
the_post_thumbnail('medium');
}
else
{
the_post_thumbnail();
}
}

Let me know if you need help


julesphoto comments:

I am using <?php the_content(); ?> to display the images on the post. How would I replace that with your code?


Hariprasad comments:

Oh. Is it possible for you to set image as featured image?


julesphoto comments:

I am using featured images but I am firstly looking for a solution to use on instances of single.php. I am currently serving on a post approx 50 images that are large size and so I was hoping to detect the browser size and swap them out if it is a small res screen like on a mobile phone.


Hariprasad comments:

Okay.

The answer provided by @Dbrans would work for your situation. You need to add separate content(with separate image) inside shortcode of post content.

2014-04-14

Sai kumar answers:

Hi,

Is your website responsive one? Then you can change the image width with @media query css. Or you can use javascript/jQuery to detect the browser width and from that you can give inline width to the image from the script itself. Reply me.

Thanks
Sai


julesphoto comments:

My website is responsive and uses media queries. I dont want to resize a very large image if it isn't needed I prefer to deliver a smaller image if the browser resolution is small.

2014-04-14

Luis Abarca answers:

Have a look to this plugin [[LINK href="https://wordpress.org/plugins/simple-responsive-images/"]]https://wordpress.org/plugins/simple-responsive-images/[[/LINK]]

2014-04-14

Dbranes answers:

You could for example try to use shortcodes in your content:


Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

[mobile] Mobile images/content [/mobile]
[desktop]Desktop images/content[/desktop]

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.


where you define the shortcodes for exampe like this:

// [mobile]
add_shortcode( 'mobile', 'mobile_shortcode' );

function mobile_shortcode( $atts = array(), $content = '' ) {
if( wp_is_mobile() )
return $content;
else
return '';
}

// [desktop]
add_shortcode( 'desktop', 'desktop_shortcode' );

function desktop_shortcode( $atts = array(), $content = '' ) {
if( ! wp_is_mobile() )
return $content;
else
return '';
}


julesphoto comments:

This is a little beyond my knowledge so I am not sure I understand. Please can you provide further explanation/instructions in very simple format?


Dbranes comments:

It's just an idea if you're images are in the content editor.

I guess you're familiar with the <em>[gallery]</em> shortcode, that you can use in your content editor?

You can always define your own shortcodes.

When you're on mobile, only the content of the [mobile] shortcode will display.

When you're NOT on mobile, only the content of the [desktop] shortcode will display.


julesphoto comments:

What does wp_is_mobile treat as mobile? I want to serve images that are always a little larger than the devices resolution.

How does it detect the mobile device as some mobile devices have very high resolution screens and so these must receive the large images. An ipad air is a mobile device but this must receive full size content..... I guess by mobile I mean mobile phones, and so specific resolutions, so for example a device with 480px screen should receive some content that is suitable for it.

I know it can get very complicated with all the different screen sizes that are around so for now I am happy to just make a solution that is 2 way.... ie if the screen res is less than x then serve smaller images otherwise leave the default.


Dbranes comments:

The function <em>wp_is_mobile()</em> doesn't give you explicit screen-size options.

I think it's detecting the <em>user-agent</em> string, like most of the PHP solutions are, for example [[LINK href="mobiledetect.net"]]http://mobiledetect.net/[[/LINK]].

One can for example construct boolean functions like <em>is_ipad(), is_tablet(), is_android()</em> that way.

Very interesting link provided by @Sébastien, that you should check out.

But you said you're including approx. 50 images per post, so I think this method is very database heavy in your case, where you have to call

1x get_attachment_id_from_src + 3x wp_get_attachment_image_src

for each image. So on an archive page with 10 - 20 posts you get very heavy database usage.

You could also modify the shortcodes to the solution provided by @Arnav Joy to use media queries:

// [mobile]
add_shortcode( 'mobile', 'mobile_shortcode' );
function mobile_shortcode( $atts = array(), $content = '' ) {
return sprintf( '<div class="mobile-only">%s</div>', $content );
}
// [desktop]
add_shortcode( 'desktop', 'desktop_shortcode' );
function desktop_shortcode( $atts = array(), $content = '' ) {
return sprintf( '<div class="desktop-only">%s</div>', $content );
}



julesphoto comments:

Is it possible to expand upon this to also check browser resolution and then serve the correct attachment size once?

<?php

$images =& get_children( array (

'post_parent' => $post->ID,

'post_type' => 'attachment',

'post_mime_type' => 'image'

));



if ( empty($images) ) {

// no attachments here

} else {

foreach ( $images as $attachment_id => $attachment ) {

echo wp_get_attachment_image( $attachment_id, 'thumbnail' );

}

}

?>


At the moment I would be happy with a solution that only serves a smaller image size for one case scenario. For example is the browser is 480px or less serve 'medium' else do nothing/leave large image size.


Dbranes comments:

Are you using cache? That might give you problem using mobile checks in PHP code.

---

I wonder if you could use javascript to modify the <em>data-src</em> attribute depending on the screen-size?

The ideal case would be if the resized images had nice names, where the original size would be included in the name:


Full size: car.jpg -> car_1200x800.jpg
Small size: car_150x150.jpg -> car_1200x800-small.jpg
Large size: car_600x400.jpg -> car_1200x800-large.jpg


We can use a filter to change the full size names to include the original width/height, but I'm not sure about the generated ones?

That's Just an idea ;-)



Dbranes comments:

Well, maybe that could be solved using a dynamic image resizer?

Are you using JetPack? If so you might consider using Photon image resizing service (CDN) with the javascript data-src replacer.

Just thinking out loud ;-)

2014-04-14

Arnav Joy answers:

for it you have to create two divs , one to hold the large image and one to hold the small image , you can write media queries to show hide div as per screen resolution