Sam Sam - 11 months ago 76
PHP Question

Switch PHP value depending on viewport size

I'm using the ACF plugin with WordPress to output images. Within my functions.php file, I have two image sizes:

add_image_size( 'full', 1024, 400, true );
add_image_size( 'square', 540, 540, true );

To work with img srcset and ACF, I have the following helper code within functions.php:

function responsive_image($image_id,$image_size,$max_width){

// check the image ID is not blank
if($image_id != '') {

// set the default src image size
$image_src = wp_get_attachment_image_url( $image_id, $image_size );

// set the srcset with various image sizes
$image_srcset = wp_get_attachment_image_srcset( $image_id, $image_size );

// generate the markup for the responsive image
echo 'src="'.esc_url($image_src).'" srcset="'.esc_attr($image_srcset).'" sizes="(max-width: '.$max_width.') 100vw, '.$max_width.'"';


Within my theme, I then have:

<img <?php responsive_image(get_field( 'image' ), 'full', '1024px'); ?> alt="<?= esc_attr( get_field('alt') ); ?>">

This outputs the following on the front-end:

<img src="test-1024x400.jpg" srcset="test-1024x400.jpg 1024w, test-300x117.jpg 300w, test-768x300.jpg 768w" sizes="(max-width: 1024px) 100vw, 1024px" alt="Image Alt">

The image cropping for this image is wide (full) at 1024px by 400px.

For mobile, I would like to switch this out to (square) 540px by 540px. I know I can achieve this by having an additional img tag with a mobile class, switching between the two images using
display: none
display: block
. The only downside to this method is the extra image that needs to loaded.

Is there way within the theme PHP that I can load conditional WordPress image sizes depending on the viewport?

Lee Lee
Answer Source

You can use some Wordpress functions that return boolean values to display different output for certain user agents.

But be warned this will return true if either a mobile phone OR a tablet is used. It cannot differentiate between the two.

A simple example:

if( wp_is_mobile() ) {
    // display your mobile/tablet related item here
} else {
    // display the desktop alternative here