Home › Forums › General Issues › get title from Image ID › Reply To: get title from Image ID
Trying to follow your various posts but it’s a little confusing.
But, you will not be able to set the “title” attribute of an image using wp_get_attachment_image(). “title” is not one of of the attributes set by this function and is not an attribute that is accepted in the forth argument of the function. https://developer.wordpress.org/reference/functions/wp_get_attachment_image/
This is how I create responsive images using ACF fields….
But before I do I would like to mention that in order to get WP to generate an srcset that there must me multiple images sizes that result in the same image width to height ratio. WP will only include images that are the same ratio. For example.
In order to generate an image tag that includes the “title” attribute you will need to use the WP function wp_get_attachment_image_src() and then built your own image tag.
// first get the image of the size you want.
$image_id = get_field('your-image-field'); // acf image field that returns ID
// size should be the larges image you want to show
$size = 'large';
// get the image
$image = wp_get_attachment_image_src($image_id, $size);
if ($image) {
// generate all tag
$alt = get_post_meta($image_id, '_wp_attachment_image_alt', true);
// get the image title
$title = get_the_title($image_id);
// set image class, this class is what will cause WP to generate src set
$class = 'size-'.$size.' wp-image-'.$image_id;
// generate image tag
$image_tag = '<img src="'.$image[0].'" width="'.$image[1].
'" height="'.$image[2].'" alt=" '.$alt.
'" title="'.$title.'" class="'.$class.'" />';
// this WP function will add the srcset and other attributes to the tag
wp_filter_content_tags($image_tag);
echo $image_tag;
}
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.