• jimmytuesday

    (@jimmytuesday)


    Hi everyone,

    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;
    }
  • The topic ‘Image Caption – Adding it to image link’ is closed to new replies.