0

I'm using the following code to pull the featured image from a post category. I have repeated this code another 3 times in my template to add different categories. I would like all the images to be the same size, but are all different sizes.

I've tried to create a new custom image thumbnail size (preview-thumb) in functions.php

add_theme_support( 'post-thumbnails' ); // this enable thumbnails
add_image_size( 'preview-thumb', 300, 185, true ); //this sets your default size

And then I'm using this code to fetch the thumbnail:

<!-- WILDLIFE SECTION -->
<?php $custom_query = new WP_Query(array ('cat' => 34, 'showposts' => 1));
query_posts($custom_query);
while($custom_query->have_posts()) : $custom_query->the_post();?>
<div class="span3">

<div class="myimage">
<a href="<?php the_permalink() ?>" rel="bookmark">
<!-- Check for post thumbnail & display it. Note - this will be the featured image of    your post -->
  <?php
    if ( has_post_thumbnail())
    {
      $thumb = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'preview-thumb' );
      echo '<img src="' . $thumb[0] . '">';
    } else {
      echo 'No post thumbnail.';
    }
  ?>
</a>
</div>

I could get around this by setting a fixed or min width, but want to avoid this if possible. Don't understand why the images are all different sizes. I've tried regenerating all thumbnails with a plugin, but that didn't help.

1 Answer 1

1

You're over-complicating your thumbnail code; all you need is this:

if ( has_post_thumbnail () ) {
  the_post_thumnail( 'preview-thumb' );
} else { ....

The problem with your version is that get_post_thumbnail_id() doesn't accept a size parameter, so that information gets thrown away. Luckily, the_post_thumbnail() does everything you need without having to fetch the url and build an html string by hand.

1
  • 1
    get_post_thumbnail_id doesn't accept a size, but wp_get_attachment_image_src does, which is what that parameter is passed to. the difference between your code and the original, is that yours will have height and width attributes on the img tag.
    – Milo
    Sep 22, 2014 at 20:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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