Puddinq.com sharing knowledge
';

Displaying responsive image in WordPress

Displaying responsive image in WordPress

Since WordPress 4.4, WordPress has its own way to display responsive images. The <img> tag can now hold a variety of sources that can be displayed based on the screen te page is viewed on.

Displaying a thumbnail image


The result:

<html>
<img width="300" height="300" src="https://www.puddinq.nl/wp-content/uploads/2017/05/amsterdam-genieten-300x300.jpg" class="alignleft wp-post-image" alt="" title="amsterdam-genieten" itemprop="image">
</html>

The source:

<?php
if ( has_post_thumbnail() ) {
    $post_thumbnail_id      = get_post_thumbnail_id( $post->ID );
    $post_thumbnail_title   = get_the_title($post_thumbnail_id);
    $post_thumbnail_alt     = get_post_meta( $post_thumbnail_id, '_wp_attachment_image_alt', true);
    the_post_thumbnail('medium', array( 'class' => 'alignleft', 'title' => $post_thumbnail_title, 'alt' => $post_thumbnail_alt));
}
?>

 

Displaying a responsive image

get existing image sizes:

echo '<pre>';
print_r(get_intermediate_image_sizes());
echo '</pre>';

output:

Array
(
    [0] => thumbnail
    [1] => medium
    [2] => medium_large
    [3] => large
)

Add image size link

add_image_size( 'custom-size', 400, 200, true );

output: (I used another function to get extra details)

Array
(
    [thumbnail] => Array
        (
            [width] => 150
            [height] => 150
            [crop] => 1
        )

    [medium] => Array
        (
            [width] => 300
            [height] => 300
            [crop] => 
        )

    [medium_large] => Array
        (
            [width] => 768
            [height] => 0
            [crop] => 
        )

    [large] => Array
        (
            [width] => 1024
            [height] => 1024
            [crop] => 
        )

    [custom-size] => Array
        (
            [width] => 220
            [height] => 180
            [crop] => 1
        )

)

Add image attribute settings for the extra size

function post_thumbnail_sizes_attr( $attr, $attachment, $size ) {
   if ( 'post-thumbnail' === $size ) {
       $attr['sizes'] = '(max-width: 709px) 85vw, (max-width: 809px) 76vw, (max-width: 909px) 67vw, (max-width: 984px) 60vw, (max-width: 1362px) 62vw, 840px';
}
   return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'post_thumbnail_sizes_attr', 10 , 3 );

 

The result:

<img width="1200" height="401" 
src="http://dev.geil.nl/wp-content/uploads/2017/05/amsterdam-genieten.jpg" // This will be picked according to screensize and sizes attribute
class="attachment-post-thumbnail size-post-thumbnail wp-post-image" 
alt="Hello world." 
sizes="(max-width: 709px) 85vw, (max-width: 809px) 76vw, (max-width: 909px) 67vw, 
(max-width: 984px) 60vw, (max-width: 1362px) 62vw, 840px">