• Skip to primary navigation
  • Skip to main content
  • Skip to footer

JH Tech Services

A knowledgebase

  • Portfolio
  • Knowledgebase
  • About

WordPress and Responsive Images

June 20, 2016 by jer0dh

Using custom fields to create a list of previous projects. When using get_the_post_thumbnail(), it will put in the responsive img tag that includes srcset and sizes attributes. When changing what size that is passed to this function, one gets a different img markup.


add_action( 'genesis_entry_content', 'eth2_front_websites', 13);

function eth2_front_websites() {

    $projects = get_field('projects');

    if ($projects) {
        echo '

' . get_field('projects_title') . '

'; echo '
    '; foreach ($projects as $project) { ?>
  • //We'll change this line to see what changes ID, 'medium'); ?>
    post_content; ?>
'; } }

If the function call is :
get_the_post_thumbnail($project->ID);
It will use the default size value of ‘post-thumbnail’. This will produce the following markup:


prism

This will almost always load the largest image. In our page design, the image will only be the full width of the screen if the screen is on mobile. On other screens it’s only about one-third the width of the screen. This is not good markup for this image in this context.

If the function call is :
get_the_post_thumbnail($project->ID, ‘thumbnail’);
This will produce the following markup:


prism

So if you do ‘thumbnail’ for size, you get just the ‘thumbnail’ size and your image markup is not responsive.

If the function call is :
get_the_post_thumbnail($project->ID, ‘medium’);
This will produce the following markup:


prism

This is about perfect for this case. sizes says the image will be the width of the screen on screen sizes 300px or smaller which is true. I don’t agree with the default setting of 300px, though. Doesn’t this mean the max width of this picture will be 300px. So in all cases only the first source in the srcset attribute will be used. Well, actually, I take that back. The browser could use the other sources if the screen density is 2x or 3x. I’m thinking a sizes=(max-width: 300px) 100vw, 33vw would be better in this design as the max-width isn’t 300px but a third of the screen size.

If we did want to change the sizes or srcset attributes, this article shows how to do it.

  • Knowledgebase
  • PHP
  • Wordpress

Footer

  • Portfolio
  • Knowledgebase
  • About

© 2023