media_buttons()
云策文档标注
概述
media_buttons() 函数用于在 WordPress 编辑器中添加媒体按钮,支持自定义编辑器 ID 和向后兼容的过滤器。
关键要点
- 函数接受一个必需的字符串参数 $editor_id,默认为 'content',用于指定目标编辑器。
- 内部处理包括递增实例计数器、获取当前 post 对象、调用 wp_enqueue_media() 来加载媒体相关资源。
- 输出一个带有 id 属性和 'Add Media' 文本的按钮 HTML,id 仅在第一个实例时设置。
- 包含一个已弃用的过滤器 media_buttons_context,用于向后兼容,建议使用 media_buttons action 替代。
- 相关函数包括 wp_enqueue_media()、__()、esc_attr() 和 get_post(),用于支持功能实现。
代码示例
media_buttons( $editor_id = 'content' ) {
static $instance = 0;
++$instance;
$post = get_post();
if ( ! $post && ! empty( $GLOBALS['post_ID'] ) ) {
$post = $GLOBALS['post_ID'];
}
wp_enqueue_media( array( 'post' => $post ) );
$img = ' ';
$id_attribute = 1 === $instance ? ' id="insert-media-button"' : '';
printf(
'%s',
$id_attribute,
esc_attr( $editor_id ),
$img . __( 'Add Media' )
);
$legacy_filter = apply_filters_deprecated( 'media_buttons_context', array( '' ), '3.5.0', 'media_buttons' );
if ( $legacy_filter ) {
if ( 0 === stripos( trim( $legacy_filter ), '' ) ) {
$legacy_filter .= '';
}
echo $legacy_filter;
}
}注意事项
- media_buttons_context 过滤器已从 3.5.0 版本起弃用,开发者应改用 media_buttons action 来扩展媒体按钮功能。
- 函数依赖于全局变量 $GLOBALS['post_ID'] 来获取 post 对象,确保在适当上下文中调用以避免错误。
原文内容
Adds the media button to the editor.
Parameters
$editor_idstringrequired
Source
function media_buttons( $editor_id = 'content' ) {
static $instance = 0;
++$instance;
$post = get_post();
if ( ! $post && ! empty( $GLOBALS['post_ID'] ) ) {
$post = $GLOBALS['post_ID'];
}
wp_enqueue_media( array( 'post' => $post ) );
$img = '<span class="wp-media-buttons-icon" aria-hidden="true"></span> ';
$id_attribute = 1 === $instance ? ' id="insert-media-button"' : '';
printf(
'<button type="button"%s class="button insert-media add_media" data-editor="%s" aria-haspopup="dialog" aria-controls="wp-media-modal">%s</button>',
$id_attribute,
esc_attr( $editor_id ),
$img . __( 'Add Media' )
);
/**
* Filters the legacy (pre-3.5.0) media buttons.
*
* Use 'media_buttons' action instead.
*
* @since 2.5.0
* @deprecated 3.5.0 Use 'media_buttons' action instead.
*
* @param string $string Media buttons context. Default empty.
*/
$legacy_filter = apply_filters_deprecated( 'media_buttons_context', array( '' ), '3.5.0', 'media_buttons' );
if ( $legacy_filter ) {
// #WP22559. Close <a> if a plugin started by closing <a> to open their own <a> tag.
if ( 0 === stripos( trim( $legacy_filter ), '</a>' ) ) {
$legacy_filter .= '</a>';
}
echo $legacy_filter;
}
}
Hooks
- apply_filters_deprecated( ‘media_buttons_context’, string $string )
-
Filters the legacy (pre-3.5.0) media buttons.
Changelog
| Version | Description |
|---|---|
| 2.5.0 | Introduced. |