Gallery Image Captions - Hide/Show
I just recalled this caption toggle question, when I was writing this answer, so let me rewrite it a little bit to work for this question.
Let's introduce the caption_toggle
attribute for the native gallery shortcode, that takes a comma separated string of bool values.
It's possible to hide the captions with CSS, but here we do it via PHP.
Example
Here are three usage examples:
[gallery caption_toggle="yes,yes,no" ids="321,132,123"]
[gallery caption_toggle="true,true,false" ids="321,132,123"]
[gallery caption_toggle="1,1,0" ids="321,132,123"]
how to control the visibility of each image caption in the gallery.
Demo Plugin
Here's the demo plugin for PHP 5.4+ to support this feature:
<?php
/**
* Plugin Name: Gallery Image Captions - Hide/Show On A Per Image Id Basis
* Description: Support for the caption_toggle attribute for the native post gallery
* Plugin URI: https://wordpress.stackexchange.com/a/228863/26350
* Version: 1.0.0
*/
namespace WPSE\Q219782;
class Main
{
/**
* @var boolean
*/
private $active;
/**
* @var array
*/
private $settings;
/**
* Setup actions and filters
*/
public function activate()
{
add_filter( 'shortcode_atts_gallery', [ $this, 'shortcode_atts_gallery' ],10,3);
add_action( 'pre_get_posts', [ $this, 'pre_get_posts' ] );
add_filter( 'the_posts', [ $this, 'the_posts' ] );
}
/**
* Get the user input for the caption_toggle attribute
*/
public function shortcode_atts_gallery( $out, $pair, $atts )
{
if( ! empty( $atts['caption_toggle'] ) )
{
$this->active = true;
$this->settings = explode( ',', $atts['caption_toggle'] );
}
return $out;
}
/**
* Don't suppress filters for the gallery posts query
*/
public function pre_get_posts( \WP_Query $q )
{
if( $this->active )
$q->set( 'suppress_filters', false );
}
/**
* Show/Hide the image caption according to the user settings
*/
public function the_posts( $posts )
{
if( $this->active )
{
foreach( $posts as $i => $post )
{
if( isset( $this->settings[$i] )
&& wp_validate_boolean( $this->settings[$i] )
)
$post->post_excerpt = '';
}
$this->active = false;
}
return $posts;
}
} // end class
/**
* Activate
*/
( new Main )->activate();
How to install: Copy this code into the /wp-content/plugins/galleries-with-caption-toggle/plugin.php
file and activate the plugin in the wp-admin backend the usual way. Then add e.g. caption_toggle="yes,yes,no"
to your gallery shortcode to control the image caption visibility.