Getting the Image Title (not the post title)

I've tried over a dozen variations of getting the title now, with mixed results. I get an error, blank output, or the post title, but not the image title.

For reference, here's the complete image code (with my latest attempt) I'm using in posts:

?php if ( has_post_thumbnail() ) : ?
a href=?php $src = wp_get_attachment_image_src( get_post_thumbnail_id( $post-ID ), 'full', false ); echo esc_url( $src[0] ); ? title=?php the_title( $attachment_id ); ??php the_post_thumbnail( 'full', array( 'itemprop' = 'image' ) ); ?/a
?php endif; ?

The specific bit I'm having difficulty with:

?php the_title( $attachment_id ); ?

Topic title Wordpress

Category Web


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. :)

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.