Site logo

Archived topic

Show different image on desktop and mobile

6 replies · Started by Rostyslav on July 24, 2022

Viewing posts 1–7 of 7

I used this structure: https://ibb.co/5kX2Y9q
Both images with same CSS class, but to image1 I added hide-on-mobile and for image2 I added hide-on-desktop.

The problem is that the browser is loading both images always: https://ibb.co/v4cv4ry

How can I avoid loading both images?

Thanks!

Hi there,

The problem is that the browser is loading both images always

Do you mean both images show in HTML? If so, it's normal.

CSS is not PHP, it can't change HTML.

But when the browser read the CSS in the site head, it will know that there's no need to load one of them depending on the devices' screen size.

Hi Rostyslav,

Yes, that would work if you don’t want to just hide the image block.

You would simply need two block elements and set the display rules depending on wp_is_mobile().

So in your case, something like this:

add_filter( 'generate_block_element_display', function( $display, $element_id ) {
    if ( wp_is_mobile() ) {
        if ( 123 === $element_id ) {
            $display = false;
        }
    } else {
        if ( 456 === $element_id ) {
            $display = false;
        }
    }
    return $display;
}, 10, 2 );

Kindly replace 123 and 456 with you Elements’ IDs.

Hello!

How can I know the id of each block elements?

Thanks!

This archived topic is closed to new replies.