add_screen_option()
Registers an option for an admin page that will be shown in the special "Screen Options" tab (in the top right corner).
Works based on the method:
WP_Screen::add_option( $option, $args = array() );
See the file /wp-admin/includes/class-wp-screen.php
The function adds the option name and its parameters to the class property $_options, which can then be obtained using the method WP_Screen::get_option( $option, $key = false )
There is also a predefined option 'per_page'. If it is defined at a time when the screen is defined but the output has not yet happened, then the screen options will include the "Pagination" setting:
It should be called after the screen is defined, i.e. during or after the action current_screen (this is after admin_init). Best during page load: action load-(page_hook).
No Hooks.
Returns
null. Nothing.
Usage
add_screen_option( $option, $args );
- $option(string) (required)
- The name of the option. Predefined names are
per_pageandlayout_columns. - $args(mixed)
- The option parameters as an array or otherwise.
Default: array()
Examples
#1 Add page navigation settings to the admin panel page
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() add screen option code WP 6.9
function add_screen_option( $option, $args = array() ) {
$current_screen = get_current_screen();
if ( ! $current_screen ) {
return;
}
$current_screen->add_option( $option, $args );
}