Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Use the WordPress Media Title and/or Caption Fields for Gallery Image Captions
* Custom Gallery Image Caption Filter
* I want to use any of the media
* attachment meta that's available. In
* this example, we'll use the image title
* and caption values for the gallery caption.
* $id is the attachment ID (i.e., media file).
* ~mlc 16 February 2020
$filtered_caption =
apply_filters( 'gallery_image_caption', $id, $captiontag, $selector, $itemtag );
// Custom: If filtered then use the new content.
if ( ! empty( $filtered_caption ) ) {
$output .= $filtered_caption;
// Custom: Else use the default WordPress caption logic.
} else {
if ( $captiontag && trim( $attachment->post_excerpt ) ) {
$output .= "
<{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'>" . wptexturize( $attachment->post_excerpt ) . "
$output .= "</{$itemtag}>";
} // Custom: else
Copy link

marklchaves commented Feb 16, 2020

Screen Capture of the Results

Gallery with the media attachment title and caption displayed using default formatting.

[gallery size="medium" columns="2" link="file" ids="68,75"]


Gallery with the media attachment title, caption, and description using a styled H4 captiontag .

[gallery size="large" columns="3" link="file" ids="29,30,31" captiontag="h4"]


Example Media Attachment Meta for Above Gallery


Gallery Image Caption with links to the image file and the media attachment.

Link to Image File and Media Attachment

Filter Used for Above Example

    return "<{$captiontag} class='wp-caption-text gallery-caption' id='{$selector}-{$id}'>" .
            "Title: " . $my_image_meta['title'] . "<br>" .
            "Caption: " . $my_image_meta['caption'] . "<br>" . 
            "Description: ". $my_image_meta['description'] . "<br>" .
            "<a href='" . $my_image_meta['src'] . "'>Download Image</a><br>" .
            "<a href='" . $my_image_meta['href'] . "'>View Attachment</a><br>" .

Copy link

Now Available as a Plugin!

I'm excited to announce the release of the official Gallery Image Captions (GIC) plugin!

GIC is a minimalist low footprint plugin that created the gallery shortcut override for you. All you have to do after activating GIC is write your filter.

If you decide to use the GIC plugin, I'd appreciate your feedback. Either post to the support forum or write a review.

GIC Logo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment