Getting the Image Title (not the post title)

The specific bit I’m having difficulty with:

<?php the_title( $attachment_id ); ?>
  • the_title() doesn’t have a post ID parameter, and the first parameter is actually a text/markup to prepend to the title. And note that attachments like images in the WordPress media library have their own posts, where the type (i.e. post_type) is attachment.

  • the_title() uses the global $post variable which references the current post in the main (WordPress) query. (therefore the function doesn’t need a post ID as a parameter)

  • the_title_attribute() also by default uses the same $post global mentioned above, so that explains the “when you’re viewing the image on a page or post, it adopts their title” in your comment.

  • Both the above functions use get_the_title() to get the post title, hence you could use that function to get the title of an image (or any other attachment in the media library) by the image/attachment ID.

    I.e. Use echo get_the_title( $attachment_id ) instead of the_title( $attachment_id ).

However, for use in an HTML attribute like the title attribute, you would want to use the_title_attribute() which sanitizes/escapes the title and works with any posts (regular Posts, Pages, attachments, etc.), but to make the function works for a specific post only, use the post argument and pass a post object, like so, which uses get_post() to get the post object:

<a href="<?php the_post_thumbnail_url( 'full' ); ?>"
    title="<?php the_title_attribute( array( 'post' => get_post( $attachment_id ) ) );
?>"><?php the_post_thumbnail( 'full', array( 'itemprop' => 'image' ) ); ?></a>

But actually looking at the source, passing a post ID, i.e. the_title_attribute( array( 'post' => $attachment_id ) ), should also work because the value is only used with get_the_title() which accepts either a post ID or object.

And note that I intentionally used the_post_thumbnail_url() in the above code.. because that’s a simpler way to display/echo the post thumbnail’s URL, for any image sizes like full, thumbnail, custom, etc. 🙂