wordpress filter set-screen-option not working

I recently tried to use screen options for a wordpress backend plugin. I wanted to use a per page variable to be able to easily manage a number of users to request.
I first init the screen options :

add_action('my_plugin_slug', array( $this, 'screen_set_option'));

function screen_set_option() {
    add_screen_option('per_page', array(
    'default'=>10,
    'label'=>__('Users per page', 'my_domain'),
    'option'=>'users_per_page'));
}

But then I couldn’t find a way to make the filter set-screen-option to work. This filter is used to filter a screen option value before it is set (https://developer.wordpress.org/reference/hooks/set-screen-option/).
I tried this code with no success :

add_filter('set-screen-option', array($this, 'set_screen_option'), 10, 3);

function set_screen_option($status, $option, $value) {
      if ( 'search_member_per_page' == $option ) {
          $user = get_current_user_id();
          update_user_meta($user, 'users_per_page', $value);
          return $value;
     }
     return $value;
}

So I choose to save the screen option value after it was posted :

// when rendering the page :

$user=get_current_user_id();
$screen=get_current_screen();

if ( isset( $_POST['wp_screen_options'] ) &&is_array( $_POST['wp_screen_options'] ) ) {
     $option=$_POST['wp_screen_options']['option'];
     if ($option=='users_per_page') {
        $users_per_page=$_POST['wp_screen_options']['value'];
         update_user_meta($user, users_per_page', $users_per_page);
          apply_filters( 'set-screen-option', false, $option, $users_per_page );
     }
} else {
    $users_per_page=get_user_meta($user, 'users_per_page', true);

    if ( empty ( $users_per_page) ||$users_per_page<1 ) {
       $users_per_page=$screen->get_option( 'per_page', 'default' );
    } else {
       apply_filters( 'set-screen-option', false, 'users_per_page', $users_per_page);
    }
}

Notice that I store the screen option value in the user meta table to be able to easily retrieved it.

 

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *