convert_to_screen()
云策文档标注
概述
convert_to_screen() 函数用于将屏幕字符串转换为 WP_Screen 对象,主要用于 WordPress 后台屏幕管理。它检查 WP_Screen 类是否存在,若不存在则输出错误信息并返回无效对象。
关键要点
- 参数:$hook_name(字符串,必需),用于确定屏幕的钩子名称(即钩子后缀)。
- 返回值:WP_Screen 对象。
- 函数内部检查 WP_Screen 类是否存在,若不存在则调用 _doing_it_wrong() 并返回一个无效对象。
- 正常情况通过 WP_Screen::get() 获取屏幕对象。
代码示例
function convert_to_screen( $hook_name ) {
if ( ! class_exists( 'WP_Screen' ) ) {
_doing_it_wrong(
'convert_to_screen(), add_meta_box()',
sprintf(
__( 'Likely direct inclusion of %1$s in order to use %2$s. This is very wrong. Hook the %2$s call into the %3$s action instead.' ),
'wp-admin/includes/template.php',
'add_meta_box()',
'add_meta_boxes'
),
'3.3.0'
);
return (object) array(
'id' => '_invalid',
'base' => '_are_belong_to_us',
);
}
return WP_Screen::get( $hook_name );
}注意事项
- 避免直接包含 wp-admin/includes/template.php 来使用 add_meta_box(),应通过 add_meta_boxes 钩子调用。
- 自 WordPress 3.0.0 版本引入此函数。
原文内容
Converts a screen string to a screen object.
Parameters
$hook_namestringrequired-
The hook name (also known as the hook suffix) used to determine the screen.
Source
function convert_to_screen( $hook_name ) {
if ( ! class_exists( 'WP_Screen' ) ) {
_doing_it_wrong(
'convert_to_screen(), add_meta_box()',
sprintf(
/* translators: 1: wp-admin/includes/template.php, 2: add_meta_box(), 3: add_meta_boxes */
__( 'Likely direct inclusion of %1$s in order to use %2$s. This is very wrong. Hook the %2$s call into the %3$s action instead.' ),
'<code>wp-admin/includes/template.php</code>',
'<code>add_meta_box()</code>',
'<code>add_meta_boxes</code>'
),
'3.3.0'
);
return (object) array(
'id' => '_invalid',
'base' => '_are_belong_to_us',
);
}
return WP_Screen::get( $hook_name );
}
Changelog
| Version | Description |
|---|---|
| 3.0.0 | Introduced. |