[Resolved] Elements header – Swapping image source based on width

Home Forums Support Elements header – Swapping image source based on width

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #1415212
    Alexandre

    Hi there,

    I just created a header element for my posts and I’m really happy with it. Only thing is I’d rather not load my full-sized featured image (1800px+) on mobile devices, but instead use a smaller source image.

    I’ve seen multiple topics that seem to be related, but nothing that seemed to answer this directly. I’m guessing it’s a bit complicated as you can’t use the srcset property on background images…

    What would be the best way to go about this?

    Thanks!

    #1415285
    David
    Staff
    Customer Support

    Hi there,

    you can add this PHP Snippet to your site:

    add_filter( 'generate_hero_thumbnail_id_size', function() {
        return 'large';
    } );

    Adding PHP: https://docs.generatepress.com/article/adding-php/

    Just change the large to the attachment size you want to display. The default is medium

    #1415299
    Alexandre

    Hey David, thanks for the answer.

    Setting it to large would indeed be an improvement, but is there a way to dynamically set a size based on the viewport?

    Something along the lines of:

    vw 1800px+ => Full
    vw 728px+ => Large
    vw 300px+ => Medium

    #1415330
    David
    Staff
    Customer Support

    Sorry i gave you the wrong filter above thats for outputing the featuered images as an attachment within the hero content.

    There isn’t any simple way of outputting the background image for responsive screen sizes with PHP without using a custom library or some half assed CSS that could lead to multiple image requests.

    The closest option is to use the wp_is_mobile() function within the ( correct ) generate_page_hero_background_image_url filter.

    Here’s an example – which will load the Medium size image when a mobile device is detected:

    add_filter( 'generate_page_hero_background_image_url', function( $image_url, $options ) {
        if ( wp_is_mobile() ) {
            $image_url = get_the_post_thumbnail_url( get_the_ID(), 'medium' );
        }
    
        return $image_url;
    }, 10, 2 );

    Note: wp_is_mobile() detects the client device not the Screen size, so it won’t repsond to just reducing a desktop browsers size.

    #1415366
    Alexandre

    Hi David, thanks again for answering.

    It does seem like there’s no easy way to go about this, however I feel using wp_mobile could give base results in regard to people using Retina tablets getting served low-quality images.

    I think I’m just gonna take then longer loading time in the end!

    #1415744
    David
    Staff
    Customer Support

    No problems, i agree 🙂 You’re welcome

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.