How to grab image alt text to use as a caption
-
I’m using a theme, which has disabled captions by default. I would like use text from the alt tag in <img> as the caption. In my child theme/postformats/format-image.php, I’m trying to set a variable $alt that pulls the alt text from each image in a foreach loop and then use that $alt as the caption.
Every function that I’ve tried fails to grab this information. In my code below, I’m using
$alt = get_post_meta($attachment), '_wp_attachment_image_alt', true);
I’ve also seen
wp_get_attachment_image
suggested, but I can’t get it to work either.Any help would be appreciated.
<?php /** * Make sure we can easily access the post ID */ global $post; /** * Set up variables */ $attachments = get_post_meta( $post->ID, '_ebor_portfolio_gallery_list', true ); $after = '</figure>'; $i = 0; $count = count($attachments); if(!( is_single() )){ $before = '<figure><a href="'. get_permalink() .'"><div class="text-overlay"><div class="info">'. get_option('blog_read_more', 'Read More') .'</div></div>'; $after = '</a></figure>'; } /** * Everything is set up, let's make sure we have anything to work with. */ if ( is_array( $attachments ) ){ /** * Now loop through everything that we found and build our gallery */ foreach( $attachments as $attachment ){ $i++; $image = wp_get_attachment_image_src($attachment, 'full'); $alt = get_post_meta($attachment), '_wp_attachment_image_alt', true); if( is_single() ){ echo '<figure class="relative"><a href="'. $image[0] .'" class="image-link-list fancybox-media" rel="portfolio"></a>'; } else { echo $before; } echo wp_get_attachment_image($attachment, 'medium'); echo '<br /><span class="caption">'. $alt .'</span>'; echo $after; if(!( $i == $count )) echo '<div class="divide40"></div>'; } }
Viewing 4 replies - 1 through 4 (of 4 total)
Viewing 4 replies - 1 through 4 (of 4 total)
- The topic ‘How to grab image alt text to use as a caption’ is closed to new replies.