Output image alt, width and height attributes. WordPress

Output image alt, width and height attributes. WordPress

grantsmith

Member
Local time
11:00
Joined
Aug 2, 2020
Messages
15

I'm currently developing my first WordPress theme and all is going fine. However, I seem to be struggling with outputting attributes of images from the media library. This seems really over complicated?

I finally worked out the alt attribute…

PHP:
<?php
$thumb_id = get_post_thumbnail_id(get_the_ID());
$alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);
if(count($alt)) echo $alt;
?>
alt="<?php echo $alt; ?>"

Although it feels very cumbersome but works. As for the width and height attributes I'm lost :)



Am I approaching this all wrong?

I just want to output alt, width and height!

 

Adam

Mr. Webwide
Administrator
Local time
11:00
Joined
Sep 24, 2019
Messages
1,257
Pronouns
he/him

Use wp_get_attachment_image_src() and it will return an array with height and width (in px). Not the alt though, so you'll have to do both. Getting this info from normal media is easier, not sure why they make post thumbnails a little more complicated. Looks good to me.

What are you using the dimensions for?

 
Last edited:

grantsmith

Member
Local time
11:00
Joined
Aug 2, 2020
Messages
15

"What are you using the dimensions for?" dimensions? am I :)

Here is my full code, perhaps it will help? At least this is what I have currently, but it doesn't work, hence why I'm here!

PHP:
<?php
$thumb_id = get_post_thumbnail_id(get_the_ID());
$alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);
if(count($alt)) echo $alt;
$width = get_post_meta($thumb_id, '_wp_attachment_image_width', true);
$height = get_post_meta($thumb_id, '_wp_attachment_image_height', true);
?>

<figure class="outer-5by4">
 <img src="<?php the_post_thumbnail_url('blog-listing'); ?>" class="inner-5by4" alt="<?php echo $alt; ?>" title="<?php the_title(); ?>" width="<?php echo $width; ?>" height="<?php echo $height; ?>">
</figure>

 

grantsmith

Member
Local time
11:00
Joined
Aug 2, 2020
Messages
15

Ah! Think I just stumbled across the answer, unless there is reason I should not be doing this?

PHP:
<?php the_post_thumbnail('blog-listing', array('class' => 'inner-5by3')); ?>

 
Top