Adding Screen Options tab to WP_List_Table
-
If you’re using WP_List_Table you can get the Screen Options tab working pretty easily. It’s the same as the tab on the right in the standard admin page for Posts.
The sample plugin Custom List Table Example at https://www.ads-software.com/plugins/custom-list-table-example/ can be modded slightly to get a Screen Options tab with checkboxes for the columns automatically shown and handled. Adding more fields to the tab takes a little more work. It’s all about timing the hooks right.
I uploaded to Github a new sample plugin that builds on Custom List Table Example. It’s called Custom List Table Screen Options Example, https://github.com/kitchin/custom-list-table-screen-options-example
Instead of modding the old plugin and doing a simple example of column checkboxes, I made it so my plugin requires the other plugin, and adds four more examples to the one in that plugin:
1. Using hooks at the right time, WP shows Screen Options for columns automatically.
2. Add ‘per_page’ to the Screen Options. WP has automatic code for this as well.
3. Add a single custom option to the Screen Options. WP has less code for this.
4. Add multiple custom options to the Screen Options. Not much harder.
The existing online tutorials I found were missing a few salient details:
* Most important: in the hook for validating updates,
set-screen-option
, pass the $value back if your plugin does not recognize the $option ! It’s probably for another plugin! (You probably loaded your hook for all admin, since you must hook early, when most of the globals are not yet set up. Parsing $_GET would be the only way to avoid that. But it’s not necessary to do so. Just look at the $option and leave it alone if it’s not yours.)* The ‘per_page’ option is special and has built-in handling code in WP. Custom options require more code. It turns out
add_screen_option()
is not that helpful. It just stores data for you to use, but you need the data before you can store it.* The concept is: you have to hook before
screen
is set up, and then again before the page starts to render. Rendering the list table itself fires on a later hook, too late for this Screen Options stuff.* You don’t need to modify anything about your
new WP_List_Table(...)
code. You don’t even need to use ascreen
parameter.* Finally, improvements are coming for WP_List_Table in WP 4.3. Mobile will get better, and there’s an idea of a primary column. It does not affect this plugin, by my testing.
* Side note, the core work on WP_List_table may lead WP to remove the @private declaration in the documentation. Some plugin devs make a copy of
class-wp-list-table.php
because of that declaration. Well, now we may need to copy the old style rules too, because th/td are changing, as well as a few css classes.
- The topic ‘Adding Screen Options tab to WP_List_Table’ is closed to new replies.