0

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.

2
  • Where do you plan on getting the alt and title dynamically from? Are you setting this when adding each image to the media library? or maybe you want to use dynamic values from the post data. Please be more specific.
    – Malisa
    Commented Sep 8, 2016 at 15:19
  • Why don't you want to use the_post_thumbnail() ?
    – birgire
    Commented Sep 8, 2016 at 15:34

1 Answer 1

2

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);
3
  • 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.
    – Malisa
    Commented 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
    Where do I add this code?
    – Rahul
    Commented Mar 14, 2019 at 12:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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