钩子文档

post_gallery

💡 云策文档标注

概述

post_gallery 过滤器用于修改默认的 gallery 短码输出。如果过滤后的输出非空,将替代默认的 gallery 模板生成。

关键要点

  • 过滤器名称:post_gallery,允许插件和主题覆盖默认的 gallery 短码输出。
  • 参数:$output(字符串,默认空)、$attr(数组,短码属性)、$instance(整数,唯一实例 ID)。
  • 用法:通过 add_filter 钩入,返回自定义输出以替换默认模板。

代码示例

add_filter( 'post_gallery', 'my_gallery_shortcode', 10, 3 );

function my_gallery_shortcode( $output = '', $atts = null, $instance = null ) {
	$return = $output; // fallback

	// retrieve content of your own gallery function
	$my_result = get_my_gallery_content( $atts );

	// boolean false = empty, see http://php.net/empty
	if( !empty( $my_result ) ) {
		$return = $my_result;
	}

	return $return;
}

注意事项

  • 从 WordPress 4.2.0 开始添加了 $instance 参数,用于唯一标识 gallery 短码实例。
  • 确保自定义函数正确处理空值,避免破坏默认回退机制。

📄 原文内容

Filters the default gallery shortcode output.

Description

If the filtered output isn’t empty, it will be used instead of generating the default gallery template.

See also

Parameters

$outputstring
The gallery output. Default empty.
$attrarray
Attributes of the gallery shortcode.
$instanceint
Unique numeric ID of this gallery shortcode instance.

More Information

This filter allows plugins and themes to override the default gallery template (i.e. what the gallery shortcode returns).

Source

$output = apply_filters( 'post_gallery', '', $attr, $instance );

Changelog

Version Description
4.2.0 The $instance parameter was added.
2.5.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example Migrated from Codex:

    Hook into the gallery shortcode and replace its output with your own.

    add_filter( 'post_gallery', 'my_gallery_shortcode', 10, 3 );
    
    function my_gallery_shortcode( $output = '', $atts = null, $instance = null ) {
    	$return = $output; // fallback
    
    	// retrieve content of your own gallery function
    	$my_result = get_my_gallery_content( $atts );
    
    	// boolean false = empty, see <a href="http://php.net/empty" rel="nofollow ugc">http://php.net/empty</a>
    	if( !empty( $my_result ) ) {
    		$return = $my_result;
    	}
    
    	return $return;
    }