Possible to add same caption to all photos in a gallery?

Gallery with the same caption to all images:

Here are two different ways to achieve this dynamically, without editing the caption for each image in the gallery.

If we use the custom attribute same_caption in our gallery shortcode:


then we can get the same caption for that gallery.

Before:
Before

After:
After
This is independently supported by the following plugins (PHP 5.4+):

Plugin #1 – Using preg_replace():

<?php
/**
 * Plugin Name: Gallery With Same Caption (#1)
 * Description: Support the same_caption gallery attribute.
 * Plugin URL:  http://wordpress.stackexchange.com/a/187938/26350
 * Author:      Birgir Erlendsson (birgire)
 * Version:     0.0.1
 */

add_action( 'init', function()
{
    add_shortcode( 'gallery', function( $attr = [], $content="" )
    {
        $output = gallery_shortcode( $attr );
        if( isset( $attr['same_caption'] ) )
        {
            $captiontag = isset( $attr['captiontag'] ) ? tag_escape( $attr['captiontag'] ) : 'dd';
            $from = "#<{$captiontag}( class="wp-caption-text gallery-caption" )([^>]*)>([^<]*)</{$captiontag}>#";
            $to   = "<{$captiontag}\\1\\2>" . esc_html( $attr['same_caption'] ) . "</{$captiontag}>";
            $output = preg_replace( $from, $to, $output );
        }
        return $output;
    } );
} );

Plugin #2: Using suppress_filters and some other hooks:

<?php
/**
 * Plugin Name: Gallery With Same Caption (#2)
 * Description: Support the same_caption gallery attribute.
 * Plugin URL:  http://wordpress.stackexchange.com/a/187938/26350
 * Author:      Birgir Erlendsson (birgire)
 * Version:     0.0.1
 */

namespace wpse\birgire;

add_action( 'init', function()
{
    $o = new GalleryWithSameCaption;
    $o->init();
} );

class GalleryWithSameCaption
{
    private $caption;

    public function init()
    {
        add_filter( 
            'shortcode_atts_gallery', 
            [ $this, 'shortcode_atts_gallery' ], 
            10, 
            3 
        );
    }

    public function shortcode_atts_gallery( $out, $pair, $atts )
    {
        if( isset( $atts['same_caption'] ) )
        {
            $this->caption = $atts['same_caption'];
            add_action( 'pre_get_posts', [ $this, 'pre_get_posts' ] );
        }
        return $out;
    }

    public function pre_get_posts( \WP_Query $q )
    {                                                                
        remove_action( current_action(), __FUNCTION__ );
        $q->set( 'suppress_filters', false );
        add_filter( 'the_posts', [ $this, 'the_posts' ] );
    }

    public function the_posts( $posts )
    {
        remove_filter( current_filter(), __FUNCTION__ );

        return array_map( function( \WP_Post $post )
        {
            $post->post_excerpt = esc_html( $this->caption );
            return $post;
        }, (array) $posts );
    }

} // end class

Leave a Comment