About design and nearby

How to get ALT text of featured image in WordPress

Posted: August 20th, 2019 | Author: | Filed under: Development, Tips and Tricks | Tags: , , , , | No Comments »

Sometimes you need to get a post’s featured image alt and echo it as text. Seems to be easy, right?

For example, I had such code for showing posts featured images as thumbnails for those posts:

  1. <img src=src="<?php the_post_thumbnail_url('post-thumbnails-home-page'); ?>" alt="" />

where

  1. if ( function_exists( 'add_theme_support' ) )
  2.  {
  3.  add_theme_support( 'post-thumbnails' );
  4.  add_image_size( 'post-thumbnails-home-page', 730, 354, TRUE );  //just my specified size for the default page  
  5.  }

To echo alt text into alt tag I created variable $alt:

  1. <?php $thumbnail_id = get_post_thumbnail_id( $post->ID );
  2.  $alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true); ?>
  3. <img src="<?php the_post_thumbnail_url('post-thumbnails-home-page'); ?>" alt="<?php echo $alt; ?>" />

Works as a charm!

Share Button

Check Related Posts:


Leave a Reply


  • + 7 = thirteen

Looking for a Freelance UX & UI designer for your project? I’m ready to jump onboard!

Let's discuss your project now