画廊图片标题-隐藏/显示
我刚在写作时回忆起这个标题切换的问题
this answer, 所以让我重写一下,来解决这个问题。
让我们介绍一下caption_toggle
属性,该属性采用以逗号分隔的布尔值字符串。
可以用CSS隐藏标题,但这里我们通过PHP来实现。
Example
以下是三个使用示例:
[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"]
如何控制库中每个图像标题的可见性。
Demo Plugin
以下是PHP 5.4+的演示插件,以支持此功能:
<?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();
如何安装:将此代码复制到
/wp-content/plugins/galleries-with-caption-toggle/plugin.php
以通常的方式在wp admin后端文件并激活插件。然后添加,例如。
caption_toggle="yes,yes,no"
到您的库短代码,以控制图像标题的可见性。