Create WordPress Settings Page For Custom Options

Sometimes it’s a good idea to have custom options/settings all in one page in admin panel. Those options then can be used anywhere when developing themes or plugins. I.e. those options can be values that are likely to change in future, so that you or someone else wouldn’t have to change it everywhere if it was hardcoded. To create WordPress settings page for custom options is fairly easy, everything can be done in functions.php file in your theme.

Create PHP Class For Settings Page

For better maintainability of our code, let’s create a PHP class in separate file called CustomSettingsPage.php in theme folder.

The class would look like this:

Let’s instantiate this class in our functions.php file:

Now you can navigate in admin panel Settings->Custom Settings Page to what we have created.

Basically, these options are saved in wp_options table in database. Here we have created custom_settings group to have custom_setting_1 and custom_setting_2, which are serialized and stored in one record.

When you will want to get those options somewhere else, just use get_option function, like this:

 

And that’s it! Now you have an easy way to handle custom options so that you or your client would have a flexible way to change those values in future.

Comments

  • yamranen david says:

    thank you very much
    how can I send this form in Ajax without refreshing the page ?

  • Thank you for this guide. For the record, this still works if you aren’t using add_options_page() and use add_menu_page(). I’m not sure what the difference is really. 🙂

    Another great tid-bit to include is a “Settings Saved” message. However, this might automatically be done if you use add_options_page(). But for those who don’t you simply need to add:

    // Add settings saved message with the class of “updated”
    if ( isset( $_GET[‘settings-updated’] ) ) {
    add_settings_error( ‘options_messages’, ‘options_messages’, __( ‘Settings Saved’, ‘your_options’ ), ‘updated’ );
    }
    // Show error/update messages
    settings_errors( ‘options_messages’ );

Leave a Reply to Ellis Benus Columbia, MO Web Developer Cancel Reply

Your email address will not be published.

*
*