2

I am trying to make the featured images retrieved by the_post_thumbnai() in the loop responsive, but can't seem to find a simplified solution.

The logic I want to implement is something like this:

If the screen size is less or equal to 728px
the_post_thumbnai('thumbnail') //Display the thumbnail size image 
Else 
the_post_thumbnai() //display the original size image

Can anyone suggest how I can do this without any plugins?

I am not a php expert, so please go easy on the lingo. Thanks in advance.

  • I don't have time to add a detailed answer right now, but you can utilise Wordpress' built in srcset generation by running the img tag through the_content filter - there's a bit of set up to it to make sure it'll work, esp. making sure the right class is on the image. – Tim Malone May 15 '16 at 3:53
0

You can't combine PHP and CSS in this way, as PHP is server-side and does not know client screen width, while CSS is client-side and does not know server functions. Instead, you could output both image sizes and then use CSS to show/hide them. eg:

<div class="image-thumbnail"><?php the_post_thumbnail('thumbnail'); ?></div>
<div class="image-fullsize"><?php the_post_thumbnail('full'); ?></div>

and CSS:

@media only screen and (max-width: 728px) {
    .image-thumbnail {display: block;}
    .image-fullsize {display: none;}
}
@media only screen and (min-width: 729px) {
    .image-thumbnail {display: none;}
    .image-fullsize {display: block;}
}

An alternative approach would be to output the one full size image and use CSS to adjust the width depending on the client screen width instead.

<div class="image-fullsize"><?php the_post_thumbnail('full'); ?></div>

with CSS:

@media only screen and (max-width: 728px) {
   .image-fullsize img {width: 200px; height:auto;}
}
@media only screen and (min-width: 729px) {
   .image-fullsize img {width: 100%; height:auto;}
}

The difference being with the first method the cropped thumbnail will be displayed but with the second the scaled full size image will be displayed for the thumbnail (and you can add more breakpoints later.)

  • Thank you very much. A brilliantly simple - yet effective - solution. Worked like a charm. :) – orandanow May 15 '16 at 23:02
0

The PHP template that generates the HTML output does not know the screen size. You can use img srcset in your template but you won't have 100% browser compatibility. Or, just use CSS to adjust the image size.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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