Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress: Get attached image height and width

Tags:

php

wordpress

In WordPress, I am grabbing attached images from a post and displaying them in an unordered list. It works great, except I need to now get the image height and width, in the same way that I got the src. This is my code:

PHP

$post_thumbnail_id = get_post_thumbnail_id( $iPostID );
foreach( $arrKeys as $key) {
    if( $key == $post_thumbnail_id )
        continue;
    $sImageUrl = wp_get_attachment_url($key);
    $sImgString = '<li><img src="' . $sImageUrl . '" alt="Thumbnail Image" /></li>';
    echo $sImgString;
}

Any idea how I can do this?

like image 533
colindunn Avatar asked Mar 09 '12 21:03

colindunn


People also ask

How do I get the width and height of an image in WordPress?

Changing WordPress Default Image sizesClick on Settings – Media. In the Media Settings, adjust the default image settings to fit your preferences. Click Save Changes to confirm.

How do you fix the width and height of an image?

The height and width of an image can be set using height and width attribute. The height and width can be set in terms of pixels. The <img> height attribute is used to set the height of the image in pixels. The <img> width attribute is used to set the width of the image in pixels.

How do I determine the size of an image for a URL?

Hover over the URL to see the pop up with all of the image properties. This pop up includes the Rendered size – the dimensions that the website needs – as well as the Intrinsic size – the dimensions of the originally image uploaded.

How do I find the image ID of a WordPress attachment?

If the attachment is an image, the function returns an image at the specified size. For other attachments, the function returns a media icon if the $icon parameter is set to true. To get attachment IDs dynamically in a template, you can use get_posts( array( 'post_type' => 'attachment' ) ) , etc.


3 Answers

You can use wp_get_attachment_image_src($attachment_id), it should return an array like ('/path/to/img.jpg',32,64) where 32 is the width and 64 is the height... Read the wordpress codex for more information on the usage of this function.

like image 83
JKirchartz Avatar answered Oct 05 '22 03:10

JKirchartz


You can also do something like this:

$image_attributes = wp_get_attachment_image_src( $attachment_id = 8 );
if ( $image_attributes ) : ?>
    <img src="<?php echo $image_attributes[0]; ?>" width="<?php echo $image_attributes[1]; ?>" height="<?php echo $image_attributes[2]; ?>" />
<?php endif; ?>
like image 21
Waqar Alamgir Avatar answered Oct 05 '22 04:10

Waqar Alamgir


@rgb_life Specify the 'full' parameter:

wp_get_attachment_image_src($id, 'full')
like image 24
Xiou Avatar answered Oct 05 '22 04:10

Xiou