Search code examples
phphtmlwordpressimage-scaling

How do I resize a wordpress featured image to be 620 width by whatever corresponding height in the loop but not permanently?


Here is the website I am attempting this on: http://increaseinwebtraffic.com/marywood/deals/

The top few deals are larger than 620 width, but the bottom ones are smaller. I tried to use the code below with no success. I've Googled around and only found permanent solutions.

<?php the_post_thumbnail( array(620,295) ); ?>

Any help is appreciated.


Solution

  • Please try the following code.

    <?php
    $thumbnail_id = get_post_thumbnail_id(get_the_ID());
    if (!empty($thumbnail_id))
    {
      $thumbnail = wp_get_attachment_image_src($thumbnail_id, 'full');
      if (count ($thumbnail) >= 3)
      {
        $thumbnail_url = $thumbnail[0];
        $thumbnail_width = $thumbnail[1];
        $thumbnail_height = $thumbnail[2];
    
        $thumbnail_w = 620;
        $thumbnail_h = floor($thumbnail_height * $thumbnail_w / $thumbnail_width);
      }
    }
    
    if (!empty ($thumbnail_url)): ?>
      <img class="thumbnail" src="<?php echo $thumbnail_url; ?>" alt="<?php the_title_attribute(); ?>"
           width="<?php echo $thumbnail_w; ?>" height="<?php echo $thumbnail_h; ?>" />
    <?php endif; ?>
    

    http://www.boxoft.net/2011/10/display-the-wordpress-featured-image-without-stretching-it/