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.
2 Answers
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.)