skip to Main Content

My code

<?php echo the_post_thumbnail( 'thumbnail' ); ?>

Returns : Like this

<img width="650" height="366" src="https://test.com/wp-content/uploads/2019/02/5c1c7adb0c92110fd79f66aa_1545370331112-650x366.jpg" class="attachment-thumbnail size-thumbnail wp-post-image" alt="" srcset="https://test.com/wp-content/uploads/2019/02/5c1c7adb0c92110fd79f66aa_1545370331112-650x366.jpg 650w, https://test.com/wp-content/uploads/2019/02/5c1c7adb0c92110fd79f66aa_1545370331112-300x169.jpg 300w, https://test.com/wp-content/uploads/2019/02/5c1c7adb0c92110fd79f66aa_1545370331112-768x432.jpg 768w, https://test.com/wp-content/uploads/2019/02/5c1c7adb0c92110fd79f66aa_1545370331112-1024x576.jpg 1024w, https://test.com/wp-content/uploads/2019/02/5c1c7adb0c92110fd79f66aa_1545370331112-255x143.jpg 255w, https://test.com/wp-content/uploads/2019/02/5c1c7adb0c92110fd79f66aa_1545370331112-1110x623.jpg 1110w, https://test.com/wp-content/uploads/2019/02/5c1c7adb0c92110fd79f66aa_1545370331112.jpg 1500w" sizes="(max-width: 650px) 100vw, 650px">

Here the altproperty value is empty.

But i need something to be filled for the alt property to fix the SEO bug.

Thanks in advance.

2

Answers


  1. Chosen as BEST ANSWER

    As Default the wordpress is getting uploaded image alternative(alt) content from the "Media" module.

    Example, enter image description here

    If the image source contains the alt content then the "the_post_thumbnail( 'thumbnail' )" will return the alt text in DOM.


  2. Add following code in your active themes functions.php

    add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes_add_alttopost', 20, 2);
    
    function change_attachement_image_attributes_add_alttopost( $attr, $attachment ){
        // Get post parent
        $parent = get_post_field( 'post_parent', $attachment);
    
        // Get post type to check if it's post you can also add to any post type
        $type = get_post_field( 'post_type', $parent);
        if( $type != 'post' ){
            return $attr;
        }
    
        /// Get title
        $title = get_post_field( 'post_title', $parent);
    
        $attr['alt'] = $title;
        $attr['title'] = $title;
    
        return $attr;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search