How to get featured image’s width and use elsewhere in template?

Try the following. First, add this piece of code to the template:

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

$image_data will now return an array containing the url, width, and height (function reference). To get the width, you might do this:

<?php $image_width = $image_data[1]; ?>

In your specific example, after adding the two pieces of code above to your template, you might do this:

<div style="width:<?php echo $image_width; ?>">

Is that helpful?

Leave a Comment