0

I am attempting to display 'alt' and 'title' attributes on a post thumbnail image, but the only attribute that actually displays as passed is 'class'. 'alt' and 'title' are missing. Any ideas what could be the cause?

$thumbnail_id = get_post_thumbnail_id(  );
$image_alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);
echo $image_alt; //correct alt attribute text
  1. echo get_the_post_thumbnail($post->ID, 'post-thumbnail', ['class' => 'classTest'] ); //works

  2. echo get_the_post_thumbnail($post->ID, 'post-thumbnail', ['alt' => 'altTest'] ); //doesn't work

  3. echo get_the_post_thumbnail($post->ID, 'post-thumbnail', ['title' => 'titleTest'] ); //doesn't work


  1. <img width="940" height="150" src="https:/...imgsrc.jpg" class="classTest attachment-post-thumbnail size-post-thumbnail wp-post-image"> classTest added

  2. <img width="940" height="150" src="https:/...imgsrc.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image"> altTest missing

  3. <img width="940" height="150" src="https:/...imgsrc.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image"> titleTest missing

1 Answer 1

0

Turns out this was caused by the following custom theme filter in functions.php. Commenting out fixed the problem.

function image_alt_tags($content) {
    global $post;
    preg_match_all('/<img (.*?)\/>/', $content, $images);
    if (!is_null($images)) {
        foreach($images[1] as $index => $value) {
            if (!preg_match('/alt=/', $value)) {
                $new_img = str_replace('<img', '<img alt="' . get_the_title() . '"', $images[0][$index]);
                $content = str_replace($images[0][$index], $new_img, $content);
            }
        }
    }
    return $content;
}
add_filter('the_content', 'image_alt_tags', 99999);

add_filter('post_thumbnail_html', 'thumbnail_filter', 99, 5);

function thumbnail_filter($html, $post_id, $post_thumbnail_id, $size, $attr) {
   // you can alter the resulted HTML here
   $html = preg_replace(array('/alt=\".*?\"/', '/title=\".*?\"/'), '', $html);
   return $html;
}

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.

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