Search code examples
wordpresspicturefill

Wordpress & picturefill implementation


I'm trying to implement responsive image in my wordpress theme. There are a few plug-ins available but the ones I tried messed up my layout.

What I would basically like to do is to replace all existing images (not only featured images or thumbnails) with responsive images, either with srcset or

My wordpress theme creates the following image sizes:

add_image_size( "maximal", "1900" );
add_image_size( "desktop", "1405" );
add_image_size( "tablet", "981" );
add_image_size( "smalltablet", "768" );
add_image_size( "mobile", "479" );

I have tried to replace img tags with a preg_replace function but I have never managed to capture all images and I'm not sure if it's the best way to do it. Some of my images have classes, some don't.

In the end, I would like to replace a simple image like this:

<img src="<destination"> id="<id>" class="<class">

by something like this:

<picture>
<source srcset="<img src for mobile" media="(max-width: 500px)">
<source srcset="<img src for small tablets" media="(min-width: 700px)">
<source srcset="<img src for tablets" media="(min-width: 950px)">
<source srcset="<img src for desktop" media="(min-width: 1200px)">
<source srcset="<img src for big screens" media="(min-width: 1600px)">
</picture>

The srcset equivalent is also ok.

Thanks! Laurent


Solution

  • i think the filter post_thumbnail_html will do the trick,, the code should like this..

    add_filter('post_thumbnail_html', 'picturefill_html', 99, 5);
    function picturefill_html(){
        $id = get_post_thumbnail_id(); // get attachment id
        $src_small = wp_get_attachment_image_src($id, 'smalltablet'); // your new image size url
        $src_large = wp_get_attachment_image_src($id, 'maximal'); // your another new image size url
        $class = $attr['class'];
    
        $html = '
        <picture>
            <source srcset="'.$src_small[0].'" media="(max-width: 500px)">
            <source srcset="'.$src_large[0].'" media="(min-width: 1200px)">
        </picture>
        ';
    
        return $html;
    }