Thursday, February 13, 2014

Wordpress: Working with image attachments (title, caption)

I found a very easy way to work with attachment images. First, you need to add this function to your theme's functions.php file:

 function wp_get_attachment( $attachment_id ) {  
      $attachment = get_post( $attachment_id );  
      return array(  
           'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),  
           'caption' => $attachment->post_excerpt,  
           'description' => $attachment->post_content,  
           'href' => get_permalink( $attachment->ID ),  
           'src' => $attachment->guid,  
           'title' => $attachment->post_title  

Based on the following example you can easily get any info you need about the attachment, including the caption and title.

 $attachment_id = get_post_thumbnail_id(get_the_ID());  
 $attachment_meta = wp_get_attachment($attachment_id);  
 echo $attachment_meta['alt'].'<br />';  
 echo $attachment_meta['caption'].'<br />';  
 echo $attachment_meta['description'].'<br />';  
 echo $attachment_meta['href'].'<br />';  
 echo $attachment_meta['src'].'<br />';  
 echo $attachment_meta['title'].'<br />';  


No comments:

Post a Comment