0

My sincere apologies if the following is completely way off as I'm new to this.

This previous answer looks like what I'm trying to find, but I'm not sure what to do with this information.

From what I can tell, I need to be working with wp_get_attachment_image to inject the alt and title text for every image in every post.

My theme is loading in post content with the_content();, and after looking at the Wordpress Developer page for the_content(); I'm guessing that this function is calling post-template.php.

The only section I can find in post-template.php that contains wp_get_attachment_image is as follows:

if ( $text ) {
    $link_text = $text;
} elseif ( $size && 'none' != $size ) {
    $link_text = wp_get_attachment_image( $_post->ID, $size, $icon, $attr );
} else {
    $link_text = '';
}

After looking over this answer, I'm guessing I need to do something like this with the above code:

if ( $text ) {
    $link_text = $text;
} elseif ( $size && 'none' != $size ) {
    $image_alt = get_post_meta( $image->id, '_wp_attachment_image_alt', true);
    $link_text = wp_get_attachment_image( $_post->ID, $size, $icon, $image_alt );
} else {
    $link_text = '';
}

I've passed the variable $image_alt in place of $attr here.

Again, I imagine this is very wrong, and my apologies.

4
  • 1
    Once an image is inserted into content it's hardcoded there as an HTML tag. If you want to add alt text you need to parse the content, insert the tags into the HTML and update the post. wp_get_attachment_image() won't be involved. That function is for use in templates. Mar 15, 2018 at 0:45
  • Wouldn't I use that function since I want this behavior default across the entire theme?
    – coffeebot
    Mar 15, 2018 at 0:53
  • 2
    When you add an image to a post it is added as HTML with the alt attribute that you give it when inserting the image. So having alt text in content is the default behaviour. What I'm saying is it's not possible to automatically update post content when the alt text of an image is changed in the media library without parsing the post content and modifying the HTML. Mar 15, 2018 at 0:57
  • Aaaaaaaah that makes sense. It's because I added the meta data after already posting. Thank you
    – coffeebot
    Mar 15, 2018 at 1:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.