add_screen_option()WP 3.1.0

Register and configure an admin screen option

No Hooks.

Return

null. Nothing (null).

Usage

add_screen_option( $option, $args );
$option(string) (required)
An option name.
$args(mixed)
Option-dependent arguments.
Default: array()

Examples

0

#1 Add page navigation settings to the admin panel page [auto-translate]

Suppose we register our page with add_menu_page() and we need to add a page navigation setting to the page:

// register the page
$hook = add_menu_page( $pg_title, $menu_title, $cap, $slug, $function );

// connect to the event when the page is loaded, but nothing is yet displayed
add_action( "load-$hook", function () {
	add_screen_option( 'per_page', array(
		'label' => 'Show on page',
		'default' => 10,
		'option' => 'my_page_per_page', // the name of the option will be written in the user's meta-field
	) );
} );

// Now you have to add the following hook to keep the option

// WP 5.4.2 Saving screen option per_page. Must be called before 'admin_menu' event
add_filter( 'set_screen_option_'.'my_page_per_page', function( $status, $option, $value ){
	return (int) $value;
}, 10, 3 );

// WP < 5.4.2. Saving screen option per_page. Must be called before 'admin_menu' event
add_filter( 'set-screen-option', function( $status, $option, $value ){
	return ( $option == 'my_page_per_page' ) ? (int) $value : $status;
}, 10, 3 );

To get the specified option where you need it, use this code:

$per_page_option = get_current_screen()->get_option('per_page');
$per_page = get_user_meta( get_current_user_id(), $per_page_option['option'], true ) ?: $per_page_option['default'];
// $per_page will be equal to 10 or how many were set...

Changelog

Since 3.1.0 Introduced.

add_screen_option() code WP 6.4.3

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

	if ( ! $current_screen ) {
		return;
	}

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