函数文档

add_screen_option()

💡 云策文档标注

概述

add_screen_option() 函数用于在 WordPress 后台注册和配置屏幕选项,允许开发者自定义管理界面的显示设置。它通过向当前屏幕对象添加选项来实现,主要支持 'per_page' 和 'layout_columns' 两种方法。

关键要点

  • 函数接受两个参数:$option(必需,选项名称)和 $args(可选,选项相关参数,默认为空数组)。
  • 仅支持两种方法:'per_page'(用于设置每页显示项数)和 'layout_columns'(用于设置布局列数)。
  • 函数内部调用 get_current_screen() 获取当前屏幕对象,并调用其 add_option 方法添加选项。
  • 自 WordPress 3.1.0 版本引入,相关文件位于 wp-admin/includes/screen.php。

代码示例

// 示例1:设置每页显示项数
add_screen_option( 'per_page', array( 'label' => 'My Label', 'default' => 1, 'option' => 'option_name' ) );

// 示例2:设置布局列数
add_screen_option( 'layout_columns', array( 'max' => 2, 'default' => 2 ) );

// 示例3:在特定钩子中使用,如网络仪表板设置
add_action( 'wp_network_dashboard_setup', function() {
    add_screen_option( 'layout_columns', array( 'default' => 2 ) );
} );

注意事项

  • 目前不支持复选框方法(checkboxes),仅限 'per_page' 和 'layout_columns'。
  • 使用时需确保在正确的上下文中调用,例如通过 add_action 钩子,以避免因 get_current_screen() 返回 null 而失效。

📄 原文内容

Register and configure an admin screen option

Parameters

$optionstringrequired
An option name.
$argsmixedoptional
Option-dependent arguments.

Default:array()

Source

function add_screen_option( $option, $args = array() ) {
	$current_screen = get_current_screen();

	if ( ! $current_screen ) {
		return;
	}

	$current_screen->add_option( $option, $args );
}

Changelog

Version Description
3.1.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    The $option parameter define the object (input or radio button) which will be printed to the screen option section.

    add_screen_option only accept 2 methods:

    • 1. ‘per_page’
    • 2. ‘layout_columns’

    Example 1:

    add_screen_option( 'per_page', array( 'label' => 'My Label', 'default' => 1, 'option' => 'option_name' ) );

    will print

    <input type="number" step="1" min="1" max="999" class="screen-per-page" name="wp_screen_options[value]" id="option_name" maxlength="3" value="1">

    Example 2:

    add_screen_option( 'layout_columns', array( 'max' => 2, 'default' => 2 ) );

    will print

    <input type="radio" name="screen_columns" value="1">
    <input type="radio" name="screen_columns" value="2" checked="checked">

    add_screen_option not support the checkboxes method yet.