Find and Use an image’s caption

I posted this at Stack Overflow but moving it here as it might be more appropriate.

In short:
How do I get and use the image caption? I’m writing a function for images in a post and I want to also get that image’s caption, if it exists, and append it to the image link.
If only there was a get_the_caption function!

Read More

In long:
I’m using a preg_replace function to add the ‘fancybox’ class and a specific rel attribute to every image in a WordPress post.

Right now, the image viewer Fancybox is configured to use a custom attribute ‘caption’ for the title of the image underneath. Where I can’t hand-code this is for posts with multiple images.

I would like the caption entered in the media uploader to be used – if there is one, left blank if not.

This is the function I am using to add ‘rel’ and ‘class’ to the images. This adds an image caption to the photo when viewed in Fancybox – but it adds the SAME caption, from one of the post images, to every single image.

How can I get each image’s caption appended to the link?? Thank you for any help!!!

add_filter('the_content', 'my_addlightboxrel');
function my_addlightboxrel($content) {

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 ) {
    $caption = $attachment->post_excerpt;
    } 
}

$pattern ="/<a(.*?)href=('|")(.*?).(bmp|gif|jpeg|jpg|png)('|")(.*?)>/i";
$replacement = '<a$1href=$2$3.$4$5 rel="postgallery" caption="' . $caption . '" class="fancybox"$6>';

$content = preg_replace($pattern, $replacement, $content);
return $content;
}

Related posts

Leave a Reply