Replace image if device is mobile

Hi, I am terrible with php, but I would like to use it to replace images on my site if the site is detected as being mobile.I want to use php vs media queries because of instances like on my tablet that is being recognized as mobile device, but because of the resolution, my site is still displayed as a desktop.This is a wordpress site and the function to detect mobile is wp_is_mobile()

With php, I want to be able to replace the id, class, and data-src, in the following code if wp_is_mobile detects phone, tablet, etc.

Here is the html containing the variables I want to replace if the device is mobile:

[caption id="attachment_4768" align="alignnone" width="110"]<img class="processimages wp-image-4768" src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" alt="Discovery" width="110" height="110" data-src="http://www.modovis.com/wp-content/uploads/2015/12/Process-DYIcon600-1.png" /> Discovery[/caption]

What I need to change in the above code if mobile with php is:

http://www.modovis.com/wp-content/uploads/2015/12/Process-DYIcon600-1.png
to
http://www.modovis.com/wp-content/uploads/2016/12/Process-DYIcon110.png
caption id="attachment_4768
to
caption id="attachment_4985
processimages wp-image-4768
to
processimages wp-image-4985

Is this possible?

Because PHP is server side programming language, so it can’t be used to detect the screen resolution. The Javascript can help you out.



1 Like

If the website is a responsive website then you could do this with media queries and strictly CSS. No JavaScript would be required doing it this way.

@enpriya is correct, you can’t do device/screen sniffing with php.
Javascript can do it, but like @Pepster64 I would prefer a html/css solution.
With css alone it’s only really practical to swap background images. To do it with actual <img>s you would have to load both versions and show/hide either one, which is not an elegant solution.
What you can do though with foreground images is use the srcset attribute to adapt the image source to suit the device, whatever its screen size or pixel density.
A couple of articles here:-

Hi enpriya, I actually have some php that currently detects mobile already. My site is structured as a fullpage scroll, this code will detect whether or not the device is mobile and disable the fullsection scroll for mobile. I was hoping to create something similar to this for an image swap if possible.

function custom_themify_theme_is_fullpage_scroll( $enabled ) {
    if( custom_is_mobile() ) {
        $enabled = false;
    }

    return $enabled;
}
add_filter( 'themify_theme_is_fullpage_scroll', 'custom_themify_theme_is_fullpage_scroll' );

function custom_is_mobile() {
	if ( empty($_SERVER['HTTP_USER_AGENT']) ) {
			$is_mobile = false;
	} elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false // many mobile devices (all iPhone, iPad, etc.)
                        || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
			|| strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
			|| strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
			|| strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
			|| strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false
			|| strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false ) {
					$is_mobile = true;
	} else {
			$is_mobile = false;
	}

	return $is_mobile;
}

Did you know there’s an official HTML specification to handle different image sizes? There’s really no need to do this in PHP.

http://responsiveimages.org/

My approach to this problem would be to render different sizes of the same image, and let the browser decide which one is the right fit for its viewport width. That’s what the responsive images spec is all about. Now because you’re using WordPress, you should take a look at its responsive images implementation: https://make.wordpress.org/core/2015/11/10/responsive-images-in-wordpress-4-4/

I also wrote a small PHP tool which generates different image sizes based on one image, which might be useful in your case: https://github.com/brendt/responsive-images/.

If you really want to use different images based on the viewport width, we’re talking about art direction. That’s where the picture element comes into view. There’s also a lot of documentation about that one on the official responsive images spec website.

To conclude: it would be a bad idea to fix this in PHP or JavaScript. It would be highly complex, not performant and unnecessary, because of the responsive images spec.

I did look up that wp_is_mobile() function that you mentioned, and yes that is php doing d=some form of “device sniffing”. But such sniffing is not so reliable.
Given the reason for this requirement, assuming this is to do with your other topic, linked for context. The issues are due to double density mobile displays specifically, wp_is_mobile() won’t condition for that, but media queries and srcset can.

<ot> I have not really closely studied the inner workings of WP. But when I saw the code for that function, it looks like WP php code is every bit as verbose as its html and css. :grimacing: </ot>

Thanks brentrose for presenting those options. Per your suggestion, Im going to look at using the picture element. From your link http://responsiveimages.org/ It shows this:

<picture>
  <source media="(min-width: 40em)"
    srcset="big.jpg 1x, big-hd.jpg 2x">
  <source 
    srcset="small.jpg 1x, small-hd.jpg 2x">
  <img src="fallback.jpg" alt="">
</picture>
<img src="small.jpg"
     srcset="large.jpg 1024w, medium.jpg 640w, small.jpg 320w"
     sizes="(min-width: 36em) 33.3vw, 100vw"
     alt="A rad wolf">

My current markup for the image is this:

[caption id="attachment_4768" align="alignnone" width="110"]<img class="processimages wp-image-4768" src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" alt="Discovery" width="110" height="110" data-src="http://www.modovis.com/wp-content/uploads/2015/12/Process-DYIcon600-1.png" /> Discovery[/caption]

Im sure my above code isn’t the best way to go about it, but this is my first site Ive ever coded so I’m still in the weeds. Also in the above code, you can see that im deferring image loading.

My objective here is to offer two images, one for desktop devices with vw min of 1200px and one image for tablets with pixel-ratio: 2. I’m targeting pixel ratio versus screen width because high res tablets in landscape for some reason are displaying my site as desktop even though they are being recognized as mobile.

If you think im on the right path incorporating the picture element into my current markup, ill go ahead and try to figure how to do it.

Sam you make a great point about double density about mobile displays, My tablet is a great example. wp_is_mobile detects my tablet as mobile, yet displays my site as a desktop in landscape, obviously ignoring the pixel ratio. Thats why I was hoping to to serve up images based on pixel density and not screen width. One image for pixel ration:1 and another image for pixel ratio:2.

To serve up an image based on pixel ratio perhaps I can integrate this:

<img src="images/space-needle.jpg"
srcset="images/space-needle.jpg 1x, images/space-needle-2x.jpg 2x,
images/space-needle-hd.jpg 3x">

into this:

[caption id="attachment_4768" align="alignnone" width="110"]<img class="processimages wp-image-4768" src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" alt="Discovery" width="110" height="110" data-src="http://www.modovis.com/wp-content/uploads/2015/12/Process-DYIcon600-1.png" /> Discovery[/caption]

Since Im deferring loading of this image, I have a placeholder data:image then the actual image uses data-src. Can data-src and srcset be used interchangeably and still achieve the image load deferring?

Yes, I believe the key to your problem is in pixel density, not whether you are viewing on Android Vs Chrome or whatever, or the size of the display.

It’s an improvement, though I linked to srcset rather than <picture> for a reason.
Picture is generally considered more for “art direction” where you are swapping one image for another mainly for the purpose of changing layout for different screens. For example, I have used it where I have a wide horizontal or tall vertical banner that is fine on large displays, but no good on small ones, as it either fills or overflows the screen, or is unreadable shrunk down. The solution is to swap it out for a less wide horizontal banner that fits nicely on a mobile.
If on the other hand you just want to swap out different scaled versions of exactly the same image, it should just be an <img> with srcset.

To serve up an image based on pixel ratio perhaps I can integrate this:

<img src="images/space-needle.jpg"
srcset="images/space-needle.jpg 1x, images/space-needle-2x.jpg 2x,
images/space-needle-hd.jpg 3x">

into this:

[caption id="attachment_4768" align="alignnone" width="110"]<img class="processimages wp-image-4768" src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" alt="Discovery" width="110" height="110" data-src="http://www.modovis.com/wp-content/uploads/2015/12/Process-DYIcon600-1.png" /> Discovery[/caption]

Since Im deferring loading of this image, I have a placeholder data:image then the actual image uses data-src. Can data-src and srcset be used interchangeably and still achieve the image load deferring?

@dave8794

This srcset demo may be useful. The images displayed are different depending on screen width. Actual usage the images would all be the same except for the browser dimensions.

http://www.johns-jokes.com/downloads/sp-h/amp-img-srcset/

Source included.

Edit:
Source is also included to create smaller images using ImageMagick. Php could also be used for resizing.

John, are you suggested that method as an alternative or because what I’m currently using probably won’t work for my purposes?

The demo highlights if the browser is shrunk and the url called the appropriate image is displayed.

View the source page to see how the different size images are called.

This thread may also be useful:

For testing purposes I would create a remote “test-imgs-001.php” file, compare different solutions and select one which best suits your requirements. Afterwards try to transfer the best solution to your WP site.

Thanks I’ll play around with that!

1 Like

For the benefit of others please supply links to your tests and the reasons why a particular solution was selected.

Will do!

1 Like

Moved to HTML thread.

Discussion continued at Image defer with srcset