Arun kumar
Arun kumar

Reputation: 1081

How to access image attribute in wordpress?

I am trying to access the alt attribute of the image from the WordPress file but don't know any function which helps in that. I want to set the last attribute of this function. The alt text will be set while uploading the image then this function should fetch the alt text and display that in the <img> tag.

<?php echo get_the_post_thumbnail( $post->ID, 'large', 'alt=' ); ?>

Upvotes: 1

Views: 1910

Answers (2)

Rakesh Rathore
Rakesh Rathore

Reputation: 11

$image_alt = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true);

With:

$image_alt = get_post_meta( $image->id, '_wp_attachment_image_alt', true);

Note: I assume that $image->id is correct because you use it later in your code and you get the expected result. Unfortunatley $image->id can not be tested because it involves WPGRADE_PREFIX.'homepage_slide_image meta field which you have not provide any information.

Upvotes: 0

Prakash Singh
Prakash Singh

Reputation: 651

Use this code

<?php $imgAlt = get_post_meta($imgID,'_wp_attachment_image_alt', true); ?>

Complete code to fetch the featured image source and the alt text

<?php 
$imgID  = get_post_thumbnail_id($post->ID);
$img    = wp_get_attachment_image_src($imgID,'full', false, '');
$imgAlt = get_post_meta($imgID,'_wp_attachment_image_alt', true); 
?>
<img src="<?php echo $img[0]; ?>"alt="<?php echo $imgAlt; ?>" />

Upvotes: 4

Related Questions