Get Image ALT Attribute Using Attachment ID

When using the_post_thumbnail() it will automatically generated the whole img tag.

But if using a custom output and manually generate the img element you need a way to figure out which value to use for the alt attribute. Here’s a function that helps you get the value for alt attribute based on the media attachment ID.

Simplest way is to just get the actual ALT value from the Media Library:

But let’s make that into a reusable function and also take it a bit further and make it less possible to end up without an ALT value.

The code is commented so you can understand what’s going on, but basically the way we get the value for ALT is we check to see if an actual ALT value is set, if not we use the caption and if no caption is set we use the title.

And at the end we sanitize the value and pass it back.

Here’s an example of how it would be used.

If you have any questions, let me know in the comments.

Tags: , ,
Previous Post

ThemeForest Category Page Update And Why It Sucks For New Items

Next Post

Simplest Method of Getting Related Posts


    • perspec
    • May 26, 2019

    Thank you, it work

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.