update_gallery_tab()
云策文档标注
概述
update_gallery_tab() 函数用于在文章有图片附件时,将图库标签重新添加到标签数组中。它通过检查 post_id 和附件数量来动态管理媒体上传器中的标签显示。
关键要点
- 函数接收一个 $tabs 数组参数,并返回更新后的数组。
- 如果未设置 $_REQUEST['post_id'] 或附件数量为空,则移除 'gallery' 标签。
- 使用 wpdb::get_var() 和 wpdb::prepare() 安全查询附件数量。
- 当有附件时,设置 'gallery' 标签并显示附件数量,例如 "Gallery (5)"。
代码示例
function update_gallery_tab( $tabs ) {
global $wpdb;
if ( ! isset( $_REQUEST['post_id'] ) ) {
unset( $tabs['gallery'] );
return $tabs;
}
$post_id = (int) $_REQUEST['post_id'];
if ( $post_id ) {
$attachments = (int) $wpdb->get_var( $wpdb->prepare( "SELECT count(*) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' AND post_parent = %d", $post_id ) );
}
if ( empty( $attachments ) ) {
unset( $tabs['gallery'] );
return $tabs;
}
/* translators: %s: Number of attachments. */
$tabs['gallery'] = sprintf( __( 'Gallery (%s)' ), "$attachments" );
return $tabs;
}注意事项
- 函数依赖于 $_REQUEST['post_id'],需确保在调用时已设置。
- 使用 wpdb::prepare() 防止 SQL 注入,确保查询安全。
- 标签文本支持翻译,使用 __() 函数进行本地化。
原文内容
Adds the gallery tab back to the tabs array if post has image attachments.
Parameters
$tabsarrayrequired
Source
function update_gallery_tab( $tabs ) {
global $wpdb;
if ( ! isset( $_REQUEST['post_id'] ) ) {
unset( $tabs['gallery'] );
return $tabs;
}
$post_id = (int) $_REQUEST['post_id'];
if ( $post_id ) {
$attachments = (int) $wpdb->get_var( $wpdb->prepare( "SELECT count(*) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' AND post_parent = %d", $post_id ) );
}
if ( empty( $attachments ) ) {
unset( $tabs['gallery'] );
return $tabs;
}
/* translators: %s: Number of attachments. */
$tabs['gallery'] = sprintf( __( 'Gallery (%s)' ), "<span id='attachments-count'>$attachments</span>" );
return $tabs;
}
Changelog
| Version | Description |
|---|---|
| 2.5.0 | Introduced. |