Ask your WordPress questions! Pay money and get answers fast! (more info)

Two Codes to Show Thumbnail if a Certain Size WordPress

  • SOLVED

I need two separate codes which utilize <?php the_post_thumbnail(); ?>

<strong>Code#1</strong>
Checks to see if the thumbnail assigned to the post is <strong>equal to or larger than X pixels wide</strong> (let's use 500px for this example), if it is <?php the_post_thumbnail('top-post'); ?> is displayed. <?php the_post_thumbnail('top-post'); ?> is a specifically sized thumbnail which I will have sized via functions.php (not a code I need, just for your information). If the image is not at 500px or wider, then nothing is displayed.

<strong>Code #2</strong>
Checks to see if the thumbnail assigned is <strong>less than X pixels wide</strong> (again, let's use 500px for this example). If it is, <?php the_post_thumbnail('bottom-post'); ?> is displayed. If the image is 500px wide or greater, nothing is displayed.

Answers (2)

2013-06-04

Remy answers:

By thumbnail do you mean Featured image ? You can get width and height of any image with wp_get_attachment_image_src() function. Here is what you can do :


<?php $image_data = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
if ( $image_data[1] >= 500 ) {
the_post_thumbnail( 'top-post' );
}

if ( $image_data[1] < 500 {
the_post_thumbnail( 'bottom-post');
}
?>


siouxfan45 comments:

Parse error: syntax error, unexpected '{' - not sure how to fix this, please advise.


Remy comments:

Forgot a ")"

<?php $image_data = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );

if ( $image_data[1] >= 500 ) {

the_post_thumbnail( 'top-post' );

}



if ( $image_data[1] < 500 ) {

the_post_thumbnail( 'bottom-post');

}

?>


siouxfan45 comments:

While the code pulls the image, it seems to be ignoring the size of the images (which is really the main function of the code) - any idea why this may be?


Remy comments:

the image sizes 'top-post' and 'bottom-post' are defined in functions.php ?


siouxfan45 comments:

Correct. Your code is generating thumbnails for top-post for all images, regardless of actual size of the original image.


Remy comments:

Can you test the actual width return by the function with :
<code></code>
<?php $image_data = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );

echo $image_data[1];

?>

And tell me the result


siouxfan45 comments:

Ahh, I see now - my images were being resized improperly. Your code works.

2013-06-05

Arnav Joy answers:

<?php


$img_d = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'full' );

//for top

if ( $image_data[1] >= 500 ) {

img_d( 'top-post' );

}


// for bottom

if ( $img_d[1] < 500 ) {

the_post_thumbnail( 'bottom-post');

}

?>