0

I'm trying to display the images in Landscape or Portrait mode depending on the width of the image I upload to the "featured image" of each WordPress article.

If the width of the image is greater than the height, it stays with the default thumb, but if the width is less, select the "image-vertical-inside-single" thumb.

I have an add_image_size( 'image-vertical-inside-single', 450, 99999, false ); So I can create the image that size.

And the following code...

 <?php
        $thumb_single            = 'imagen-vertical-inside-single';
        $imgData     = wp_get_attachment_metadata( get_post_thumbnail_id( get_the_ID() ) );
        $width       = $imgData['width'];
        $height      = $imgData['height'];

        if ( $width > $height || $width == $height ) {
            $thumb_single = '';
        } else {
            if ( '' != get_the_title() ) {
                $thumb_single = 'imagen-vertical-inside-single';
            }
        }

        return $thumb_single;

?>

            <figure class="featured-image">
                <?php the_post_thumbnail( $thumb_single, array('class' => 'skip-lazy') ); ?>
            </figure>

But it doesn't work properly...

0

I think the problem is that you're trying to get the metadata for an image without specifying which size you want the width and height from.

    $imgData     = wp_get_attachment_metadata( get_post_thumbnail_id( get_the_ID() ) );
    $width       = $imgData['width'];
    $height      = $imgData['height'];

Instead try this:

    $imgID       = get_post_thumbnail_id( get_the_ID() );
    $imgURL      = wp_get_attachment_image_src( $imgID, 'full' ); // now I know which image specifically I want - in this case 'full'.
    $width       = $imgURL['1']; // I've never tested 'height' and 'width', but 100% the array numbers work
    $height      = $imgURL['2'];

Now I know the height and width of the specific img url I'm testing.

| improve this answer | |

Your Answer

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

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