1

I'd like to be have more control on the srcset on certain important images of my website if not all.

By default the srcset includes all the sizes created by wordpress for all the images. I'd like to be able to choose which sizes will be taken among all the different sizes created by wordpress.

To be very clear here is an example : - I have lots of thumbnails images in a page listing all my articles. - maximum width of this thumbnail : 250px taking count of all the different screens and resolutions - I upload my thumbnail at a resolution much higher than needed lets say 2000px wide. In my case 10 images are generated at these sizes :

thumbnail (150x150)
medium (600x600)
medium_large (700x700)
large (800x800)
featured-blog (719x1020)
featured-blog-mobile-3x (1350x1915)
pleine-largeur (910x910)
colonne (460x460)
encart (340x240)
mini-size (300x300)
thumbnail-blog (246x180)
thumbnail-blog-mobile-3x (500x365)

In mobile 3x (pixel density) The image used is much too heavy : 

250px X 3 = 750px. Consequently it loads this one "large (800x800)" I want to avoid such a big image to be used as I have 70 images of that kind on the page. The page weight 30MO. Much too much !

So what I'd need is to define among the different sizes served in the srcset which one I want to include and exclude the one I don't want.

Thanks already, I would be so thankful if you could help me on this one

François

2 Answers 2

3

There is a filter max_srcset_image_width that lets you limit the sizes used in a srcset attribute to those that are less than a given maximum width.

This code will make it so that only sizes < 500 pixels wide will be used in the srcset:

/**
 * @param int   $max_width  The maximum image width to be included in the 'srcset'. Default '1600'.
 * @param array $size_array Array of width and height values in pixels (in that order).
 */
function wpse_316853_srcset_maximum_width( $max_srcset_image_width, $sizes_array ) {
    return 500;
}
add_filter( 'max_srcset_image_width', 'wpse_316853_srcset_maximum_width', 10, 2 );

In your case though, you might only want to apply this limit when the original image is your 250px wide thumbnail. $sizes_array contains the sizes of the current image, so you can use that to check:

/**
 * @param int   $max_width  The maximum image width to be included in the 'srcset'. Default '1600'.
 * @param array $size_array Array of width and height values in pixels (in that order).
 */
function wpse_316853_srcset_maximum_width( $max_srcset_image_width, $sizes_array ) {
    if ( $sizes_array[0] === 250 ) {
        $max_srcset_image_width = 500;
    }

    return $max_srcset_image_width;
}
add_filter( 'max_srcset_image_width', 'wpse_316853_srcset_maximum_width' );

Or you could do it dynamically, so that the srcset will only include images up to 2x the width of the original image:

/**
 * @param int   $max_width  The maximum image width to be included in the 'srcset'. Default '1600'.
 * @param array $size_array Array of width and height values in pixels (in that order).
 */
function wpse_316853_srcset_maximum_width( $max_srcset_image_width, $sizes_array ) {
    return $sizes_array[0] * 2;
}
add_filter( 'max_srcset_image_width', 'wpse_316853_srcset_maximum_width' );
0
0

Thanks Jabob and sorry for the late answer. It took me time to understand just a bit and test things. I lack wordpress and php knowledge. This short article helped me as well as I use ACF (advanced custom fields) : https://awesomeacf.com/responsive-images-wordpress-acf/

I could completly manage the srcset and sizes of the main image of my articles (single.php). But not the thumbnails of each articles in my blog page (taxonomy.php)

I did something close to what you wrote in your 2nd and 3rd code and it worked. The alt attribute only doesn't work unfortunatly for no reason I understand. Here is what I did :

in function.php :

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

    function remove_max_srcset_image_width( $max_width ) {
        $max_width = 1350;
        return $max_width;
    }
    add_filter( 'max_srcset_image_width', 'remove_max_srcset_image_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="'.$image_src.'" srcset="'.$image_srcset.'" sizes="(max-width: 449px) 120vw, (max-width: 767px) 576px, (max-width: 1365px) calc( 100vw - 60px - 55% ), '.$max_width.'"';

    }
}

In single.php :

<?php $img = get_field('image_principale'); ?>
        <div class="feature-image">
             <?php if( $img  ): ?>
                 <img <?php responsive_feature_image($img,'featured-blog','719px'); ?>  alt="<?php echo $img['alt']; ?>" />
            <?php else: ?>
                <img src="<?php echo get_template_directory_uri() ?>/dist/images/article/feature-image-default.jpg" alt="Illustration de l'article">
            <?php endif; ?>
        </div>

Unfortunatly I couldn't find out how to achieve the same for the thumbnails images of my blog page in the file taxonomy.php. The thumbnails are sorted by categories by a filter menu. It explains that the code is much much more complicated. Just in case you can help me some more.

Here is how the thumbnails are called in taxonomy.php :

    <?php $displayCurrentCat = get_field('display_articles-in-page_by_category', $term); ?>

    <?php if(!$displayCurrentCat && $children): ?>

        <nav class="filter_by_category">
            <ul>
                <?php if( $children ): ?>
                    <li>Filtrer les articles </li>
                    <li data-filter="all" class="actif">
                        <a href="#">Toutes les catégories</a>
                    </li>
                    <?php foreach( $children as $child ): ?>
                        <?php $child_term = get_term($child) ?>
                        <li data-filter="<?php echo $child_term->term_id; ?>" >
                            <a href="#"><?php echo $child_term->name; ?></a>
                        </li>
                    <?php endforeach; ?>
                <?php endif; ?>
            </ul>
        </nav>

    <?php endif; ?> 

    <div class="all_the_articles tdm__posts <?php if(!$displayCurrentCat){ echo'filtr-container'; } ?>">
        <?php if($displayCurrentCat): ?>
            <div class="tdm__grid tdm__grid--5">
                <?php render_term_thumbnails($term); ?>
            </div>
        <?php else: ?>
            <?php if( $children ): ?>
                <?php foreach( $children as $child ): ?>
                    <?php $child_term = get_term($child) ?>
                    <div class="filtr-item" data-category="<?php echo $child_term->term_id; ?>" data-sort="value">
                        <div class="nom_categorie tdm__posts__cat" >
                            <h2><?php echo $child_term->name; ?></h2>
                        </div>
                        <div class="tdm__grid tdm__grid--5">
                            <?php render_term_thumbnails($child); ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        <?php endif; ?>
    </div>

</div>

Here is what's in function.php :

function render_content_thumbnail($id){
    $img = get_the_img(get_field("thumbnail", $id), "thumbnail-blog");
    if(!$img){
        $img = '<img src="'.get_template_directory_uri() . '/dist/images/default_thumb.png" class="attachment-thumbnail-blog size-thumbnail-blog" alt="default '.get_the_title($id).'">';
    }
    $title = get_field('titre_court', $id) ? get_field('titre_court', $id) : get_the_title($id);
    echo '
        <article class="reveal tdm__post tdm__post--'.$id.' '.get_field('couleur', $id).'">
            <a class="tdm__post__link" href="'.get_permalink($id).'">
                <span class="tdm__post__thumbnail">'.$img.'</span>
                <span class="tdm__post__title">'.$title.'</span>
            </a>
        </article>';
}

function render_term_thumbnails($term){
    $t = get_term($term);
    $args = array(
        'post_type' => 'article',
        'orderby' => 'menu_order',
        'order' => 'ASC',
        'tax_query' => array(
            array(
                'taxonomy' => 'categorie',
                'field'    => 'slug',
                'terms'    => $t->slug
            ),
        ),
    );
    $tdmQuery = new WP_Query( $args );
    while ( $tdmQuery->have_posts() ) : $tdmQuery->the_post();
        render_content_thumbnail( get_the_id() );
    endwhile;
    wp_reset_postdata();
}

function render_term_menu($term){
    $t = get_term($term);
    $args = array(
        'post_type' => 'article',
        'orderby' => 'menu_order',
        'order' => 'ASC',
        'tax_query' => array(
            array(
                'taxonomy' => 'categorie',
                'field'    => 'slug',
                'terms'    => $t->slug
            ),
        ),
    );
    $tdmQuery = new WP_Query( $args );
    while ( $tdmQuery->have_posts() ) : $tdmQuery->the_post();
        render_content_menu( get_the_id() );
    endwhile;
    wp_reset_postdata();
}
function get_the_img($att_id, $size, $diapo = false){

    if( $att_id  ){
        $imgSrc = wp_get_attachment_image_src($att_id, $size);
        $srcset = wp_get_attachment_image_srcset($att_id, $size);
        $sizes = wp_get_attachment_image_sizes($att_id, $size);
        if(function_exists( 'get_rocket_option' ) && get_rocket_option( 'lazyload' ) && !is_user_logged_in() ){
            $i = '<img width="'.$imgSrc[1].'" class="-is-lazy" height="'.$imgSrc[2].'" data-lazy-src="'.$imgSrc[0].'" alt="'.$imgSrc[3].'" data-lazy-srcset="'.$srcset.'" sizes="'.$sizes.'">';
        }else {
            $i = '<img width="'.$imgSrc[1].'" height="'.$imgSrc[2].'" src="'.$imgSrc[0].'" alt="'.$imgSrc[3].'" srcset="'.$srcset.'" sizes="'.$sizes.'">';
        }

        $legend = wp_get_attachment_caption($att_id);

        $credit = get_field('credit', $att_id);

        $i = $diapo ? sprintf( '<div class="effet_photo">%1$s</div>', $i ) : $i;

        $i = $legend || $diapo || $credit ? sprintf( '%1$s<p class="description_photo">%2$s<span>%3$s</span></p>', $i, $legend, $credit ) : $i;

        return $i;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.