@CLE_Ren got any templates/examples to follow?
— Ben Weiser (@benweiser) March 19, 2016
Sign up or log in to view code
View CodeAfter Ben tweeted his disdain for the WordPress Settings API, a common pain in the ass for WordPress developers, I shared how I typically handle custom settings pages. This post shows a basic template of my process, which involves creating a custom form, then processing the input myself. In my opinion, this method is much simpler than the Settings API, and, also, more flexible.
Take a look, and I’ll explain below.
Sign up or log in to view code
View CodeFirst off, this code sets up a menu page in the WordPress admin. It is a top-level page, which means it gets its own top-level menu link, as opposed to a submenu page, which falls under a top-level menu item.
Next, the myplugin_render_settings_page()
function renders the markup for the settings page. In an actual plugin, I’d pull out this markup into a separate template file, but it’s fine here for the sake of convenience.
The markup I used was obtained thanks to the WP Admin Style plugin. If you’re a WordPress developer, you should be using this plugin!
Lastly, the myplugin_process_settings()
function runs some security and privilege checks, then processes the form’s input. This sample settings page submits input that will be used to add only one option to the database. If you’re using multiple settings, it is recommended that you save them all in an array, then save the array, rather than saving each setting to a separate row.
If you have any questions about the code, feel free to post them below.
Mike says
Are there ANY advantages at all that you can think of to using the wordpress settings api over your method (perhaps with security, performance or being future proof)?
I also find the settings api frustrating and would love a good alternative, but am concerned about security and other issues.
Ren says
I can’t think of anything off the top of my head, except for that it may take a bit more time, since you’re creating and processing your own form and submissions. However, I find this to be easier than the Settings API because I know exactly what is going on. For security, you have to properly sanitize incoming data whether you use the Settings API or my method. As long as you’re using proper sanitization and escape methods, you should be good as far as any injections go. There’s also a nonce field in the code I provided, which protects against unauthorized requests.
Some people may prefer to use the Settings API because it’s what WordPress provides. I’m normally all for using WordPress APIs, but the Settings API is one exception, because it sucks. With this method, I know exactly what’s going on, and I can customize the process without wanting to smash something! 😉