WordPress get attachment image caption

I tried to get attachment meta caption value as mentioned here, but couldn`t get any output. Other meta arrays like [created_timestamp] or [iso] gave their values.

$img_meta = wp_get_attachment_metadata( $id );
echo $img_meta[image_meta];

This issue happens to both and [title]. Any help is much appreciated.

Related posts

3 comments

  1. The caption and title you are looking to get from wp_get_attachment_metadata are not the title and caption you add in WordPress they are meta data from the actual image itself. To get the WordPress data use something like this (assuming $id is the id of your image).

    $image = get_post($id);
    $image_title = $image->post_title;
    $image_caption = $image->post_excerpt;
    
  2. put this in your functions.php file:

    function show_caption_image($type='title'){
      global $post;
        $args = array( 'post_type' => 'attachment', 'orderby' => 'menu_order', 'order' => 'ASC', 'post_mime_type' => 'image' ,'post_status' => null, 'numberposts' => null, 'post_parent' => $post->ID );
    
        $attachments = get_posts($args);
        if ($attachments) {
            foreach ( $attachments as $attachment ) {
          $alt = get_post_meta($attachment->ID, '_wp_attachment_image_alt', true);
          $image_title = $attachment->post_title;
          $caption = $attachment->post_excerpt;
          $description = $image->post_content;
        }
      }  
      return $type == 'title' ? $image_title : $caption.$description;
    }
    

    and below the image in your theme, or wherever you prefer to put it, usually in the single.php file:

    <?php if ( has_post_thumbnail() ) : 
            ?>
          <span class="image main"><img src="<?php echo get_the_post_thumbnail_url()?>" alt="<?php echo get_the_title()?>" /><i><?php echo show_caption_image();?></i></span>
          <?php endif; ?> 
    

Comments are closed.