1

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!

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;
}
  • This seems to be a PHP error, your $replacement is outside the foreach loop. Also why do all this heavy parsing when you can just use straight js. – Wyck Mar 15 '14 at 0:38
  • Since you already have the WP-specific component (ie. the caption is the post_excerpt of an attachment) the preg_replace part probably does belong on SO. Though I agree with Wyck, it seems like overkill. I think the JS can select the images, and couldn't you configure the image alt tags to be the captions? – helgatheviking Mar 15 '14 at 10:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.