1

The image alt tag shows the post title in the source instead of the Alt Text.

function my_custom_image_sizes() {
    add_image_size('homepage-thumb', 329, 185, true);
}
add_action('after_setup_theme', 'my_custom_image_sizes');

function my_custom_thumbnails($html, $post_id, $post_image_id, $size, $attr) {
    if(is_home() && $size == 'large') {
        $size = 'homepage-thumb';
    } elseif(is_single() && $size == 'large') {
        $size = 'postpage-thumb';
    }

    $image = wp_get_attachment_image_src($post_image_id, $size);
    if ($image) {
        $html = '<img src="' . $image[0] . '" width="' . $image[1] . '" height="' . $image[2] . '" alt="' . get_the_title($post_id) . '">';
    }

    return $html;
}
add_filter('post_thumbnail_html', 'my_custom_thumbnails', 10, 5);

I just want the alt text that I put in the image section.

2 Answers 2

2

In the place where you use get_the_title($post_id) you need to get the alt attribute that is stored in the post metadata like this:

esc_attr (get_post_meta ($post_id, '_wp_attachment_image_alt', true))
2

You can use _wp_attachment_image_alt like @cjbj shows but I am adding an addition to it for the fall back.

   $alt_text = get_post_meta($post_image_id, '_wp_attachment_image_alt', true);
          // If ALT text is not set, fallback to the post title
         if (empty($alt_text)) {
             $alt_text = get_the_title($post_id);
           }

Please always use Fall Back for the such conditions as it will cause issue if there is no ALT tag found.

Not the answer you're looking for? Browse other questions tagged or ask your own question.