I want to use the code <img class="img-responsive" src="<?php echo the_post_thumbnail_url(); ?>" alt="" />
instead of <?php the_post_thumbnail(); ?>
, to output the post thumbnail. Now, how can I get "alt" and "title" dynamically for post thumbnail. Is there any function provided by wordpress for this. I looked for a function from wordpress codex/developer site for this problem but I didn't find one.
1 Answer
Why would you want to avoid the_postthumbnail
? It can give you the exact html you want if you use the right attributes. Anyway, you can access the title and alt tags of an image like this:
// get the ID of the featured image
$thumbnail_id = get_post_thumbnail_id( $post_id );
// retrieve title (an image is a post, so you can access the title as if it is a post title)
$title = get_post($thumbnail_id())->post_title;
// retrieve alt (which is stored as metadata to a post)
$alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);
-
OP, bare in mind... You can only access the alt and title tags using the above functions if you have ACTUALLY set them in your media, otherwise they will be empty.– MalisaCommented Sep 8, 2016 at 16:05
-
Thanks. You helped me third time in my problems. Thanks again a lot. Commented Sep 12, 2016 at 14:49
-
1
the_post_thumbnail()
?