0

I've struggled with this for years. I have a category page where I want to show the post summaries in a card format using the featured image (260 x 175px). enter image description here I have created a custom image size

add_theme_support('post-thumbnails');
add_image_size( "card", 520, 350, true );

The sizes are double because of 2x mobile phone screens (have I understood responsive image sizes correctly?)

Then I have my category page which loops over the relevant posts and passes each one to this code:

if ( has_post_thumbnail() ) {
    $featuredImgTag = get_the_post_thumbnail($post->ID, 'card');

    // if no featured image, look for first image in post
    if ($featuredImgTag == "") {
        $featured = getFirstImageUrl();
    } else {
        $featured = getSrcFromImg($featuredImgTag);
    }
} else {
    $imgUrl = getFirstImageUrl();

    if (!$imgUrl) {
        $featured = "/wp-content/themes/af2015/dist/images/artichoke2.jpg";
    } else {
        $featured = $imgUrl;
    }
}
?>

<!-- I want to use the image as background in a card -->
<div class="card__image" style="background-image:url(<?php echo $featured; ?>)"> 
</div>

This is where things get weird

  • the_post_thumbnail returns an <img> tag that shows signs of having the right height and width attributes but then includes the biggest photo on the system, not the 'card' version
  • I can't find a way just to get the url , so I have to do a regex to get that.

Can anyone advise on how best to use Wordpress in such a context?

  • if you added the images before the size, the images have to be regenerated – inarilo Jun 3 '17 at 14:44
  • 1
    see user comments developer.wordpress.org/reference/functions/add_image_size – inarilo Jun 3 '17 at 14:45
  • thx, I'm making some progress – Simon H Jun 3 '17 at 15:29
  • 1
    If the width and height attributes are correct but WP loads the full image instead, that can sometimes mean that your server failed to remake all the image versions correctly. FTP in the uploads directory and see if all the expected files have been generated. If not then you may need to add RAM or tweak your PHP settings to allow WP to use more RAM, or to allow more time for PHP processes to run. – Andy Macaulay-Brook Jun 8 '17 at 17:34

Your Answer

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

Browse other questions tagged or ask your own question.