Create a simple WordPress custom option using settings API

Create a simple WordPress custom option using settings API

Prerequisite:

  • A working WordPress setup.

For the learning purpose I am going to use a blank theme that I have created. It will help us to keep things clean and easy to understand, and I prefer the file/folder structure if you want to create a WordPress theme from scratch. Basically the plan is to make a premium WordPress theme using this and I surely will share the development path step by step once things are at its good shape. Download the blank theme from the link below.

Downloadhttps://www.dropbox.com/s/ab1b0cqzjo6uudf/sunsettheme.zip

(If you do not want to use this and you prefer to work on your own file in your own way that is completely fine you are welcome)

Let’s move on, once you have downloaded the file, place it inside your WordPress theme directory and activate it from the admin panel. I like to keep things clean and I am not going to put all the codes inside the functions.php. I will put all the codes inside the inc directory and call them from functions.php.

Create A Custom Menu Page:

To create a custom option first we need a custom admin page where we will place the custom option. To do so let’s first create a .php inside the inc folder and name it function-admin.php.

FILE: inc/function-admin.php

Now, as we have our file where we gonna put all our code lets import it inside the functions.php already. Open up the functions.php file and write down the below code to import the file. Make sure you open the <?php tag.

require get_template_directory() . '/inc/function-admin.php';

Now that we have our files and folders ready let’s get into coding. First thing comes first, before we start writing any sort of code or start using any WordPress functions or hooks I would like to put some bit of comments in beginning of the file so that people can understand what exactly this file for, or at least it will make some sense, at least for me 🙂

Open up the /inc/function-admin.php file and write down the below code:

/**
 *
 * @package sunsettheme
 *
 * ==========================
 *      THEME ADMIN PAGE
 * ==========================
 */

You might think what the hell, I talked a lot about writing comment to give the file some sense and I am just writing two lines! Honestly that’s enough, you still don’t agree, that’s because you are not used to it haha…

Okay, to create a admin page or a top-level menu page we will have to use a built in function which is add_menu_page()



add_menu_page( string $page_title, string $menu_title, string $capability, string $menu_slug, callable $function = '', string $icon_url = '', int $position = null )

Read more details here – https://developer.wordpress.org/reference/functions/add_menu_page/

Ok enough talking, let’s create the admin page now. Write following code to create the admin page:

function sunset_add_admin_page() {
	// Generate Sunset Admin Page
 	add_menu_page( 'Sunset Theme Option', 'Sunset', 'manage_options', 'sunset_option', 'sunset_theme_create_page', 'dashicons-hammer', 110 );

}
add_action('admin_menu', 'sunset_add_admin_page');

Now if you go to you admin panel you will see there is an extra menu called Sunset after Settings menu item. If you go Sunset menu you will get a warning and that is obvious, because we called an undefined function sunset_theme_create_page. We will come back to this in a bit, we need to take care of something else first.

Before I move forward, one more thing that I need to talk about. If you follow the code above, as $icon_url I have used dashicons-hammer. WordPress has a built in font icon library which is called Dashicons. This is similar to Font Awesome, Glyphicons or other font icons libraries. You can check out all the available dashicons from here – https://developer.wordpress.org/resource/dashicons/

Create A Custom Sub Menu Page:

Let’s move forward, now that we have the main admin menu item we can now create a sub menu page under it. The function to create submenu page is create_submenu_page().



add_submenu_page( string $parent_slug, string $page_title, string $menu_title, string $capability, string $menu_slug, callable $function = '' )

Reade more details from here – https://developer.wordpress.org/reference/functions/add_submenu_page

Write the below code inside the function sunset_add_admin_page()

// Generate Sunset Admin Sub Page
add_submenu_page( 'sunset_option', 'Sunset Theme Settings', 'Theme Settings', 'manage_options', 'sunset_theme_settings', 'sunset_theme_setting_page' );

Now go to admin panel and click on Sunset menu and observe. Strange right!? We have created a submenu page called Theme Settings then how come there is another submenu item called Sunset? The answer is when you create submenu under a top-level menu page it looks for a default subpage and if you do not assign any it generates a submenu item with the same name of its’ parent as a default submenu page. So let’s define a default submenu page for Sunset menu.

The trick is very simple, we will set the subpage $menu_slag as same as its parent $menu_slag , in our case which is manage_options and we gonna use the same function as the callback function for both parent and subpage which is sunset_theme_create_page. Add the below code to make default sub menu page:

// Default menu page
add_submenu_page( 'sunset_option', 'Sunset Theme Option', 'General', 'manage_options', 'sunset_option', 'sunset_theme_create_page' );

If you go to the Sunset menu you will see there are two submenu page now one is General and Theme Settings, and General is the default page for Sunset menu.

We have successfully created our admin menu and also two submenu page but both of them are blank, to be more precise both are giving a warning that the required functions are missing. Lets get rid of it. First create the function for the General page:

function sunset_theme_create_page() {
    echo "

Sunset Theme General Settings

"; }

Create Custom Option:

The three function that we need to know about to create a custom option are:

  1. register_setting() – Registers a setting and its sanitization callback.

    register_setting( string $option_group, string $option_name, callable $sanitize_callback = '' )

    Details: https://codex.wordpress.org/Function_Reference/register_setting

  2. add_settings_section() – Adds a new section to a settings page.

    add_settings_section( string $id, string $title, callable $callback, string $page )

    Details: https://codex.wordpress.org/Function_Reference/add_settings_section

  3. add_settings_field() – Adds a new field to a section of a settings page.

    add_settings_field( string $id, string $title, callable $callback, string $page, string $section = 'default', array $args = array() )

    Details: https://codex.wordpress.org/Function_Reference/add_settings_field

So to create a custom option first we will have to register a settings option then we will register an option group or section and we will create our option field and link it with the section. Follow below code to do so:

function sunset_custom_settings() {
    register_setting('sunset-settings-group', 'first_name');
    add_settings_section('sunset-custom-options', 'Custom Theme Options', 'sunset_custom_options', 'sunset_option');
    add_settings_field('sunset-name', 'First Name', 'sunset_option_name', 'sunset_option', 'sunset-custom-options');
}
// Active custom settings
add_action('admin_init', 'sunset_custom_settings');

We just registered the custom settings and registered an option which is sunset-name. Now let’s create the field for this sunset-name custom option and save the value to the database. If you follow the code we have called two functions one is sunset_custom_options and another one is sunset_option_name. Let’s first define the first function, this will just print a message in the settings section that we just registered.

function sunset_custom_options() {
    echo "Customize Your Theme Information";
}

This is not mandatory we could keep the function callback blank I am doing it just for demonstration purpose. The important thing that we will have to do is create an input field for our custom option and we will do it inside the sunset_option_name function. Let’s define the function:

function sunset_option_name() {
    $firstName = esc_attr( get_option('first_name') );
    echo '';
}

So what is going on here, as we have registered our custom option already we are getting the value of it from the options table in the database. Here I am using a built in function esc_attr(), which is very handy to get rid of any HTML attributes. After that I am creating the input field for our first_name custom option that we have registered previously.

Okay we are done with all the defining and registration part. We have our custom option and pages ready now we need a way to print the custom option in our custom page.

To keep things neat and clear I will do those printing work in a separate template file. The idea is to create a template file for each custom page (or maybe for sections) that will call the settings and custom options to populate the page or section of the page.

I will place the custom option inside the Theme Settings page for now. Let’s create the function for the Theme Settings page.

function sunset_theme_setting_page() {
    require_once( get_template_directory() . '/inc/templates/sunset-admin.php');
}

Create a folder templates inside the inc folder and create the file sunset-admin.php. Open up the /inc/templates/sunset-admin.php file and write below code:

Sunset Theme Options

<?php settings_errors(); ?>
<?php settings_fields('sunset-settings-group'); ?> <?php do_settings_sections('sunset_option'); ?> <?php submit_button(); ?>

Lets’ talk about what is going on here. First line pretty much self-explanatory, it is a heading tag and it will print a line as a heading.

After that I have called a function settings_error(), what this function will do is it will look for any error while saving or retrieving any options data and will print it out at the top of the page. This will also notify that the data is successfully saved.

settings-saved

Then we have started a form with method=”post” and action=”options.php”. Please make sure you always do that. You always have to submit the custom options data to the options.php unless otherwise you have created a custom handler for it. What this will do is it will check the data, save it to the database if everything is alright then return you back to the page with some information about the task is done successfully or not.

The next function I use is settings_fields(), this function prints action and option page fields for a settings page. Inside the function we are calling our option group sunset-settings-group that we have defined earlier in our function-admin.php. Check the below line to recall:

register_setting('sunset-settings-group', 'first_name');

Check more details about this function here – https://codex.wordpress.org/Function_Reference/settings_fields

After that I have called do_settings_section() and passed sunset_option. What this function does is it prints all the settings sections and fields added to a particular settings page, in our case our page is sunset_option. We have created a settings section sunset-custom-options and field inside it sunset-name, so this will print the section and the field in our Theme Settings page. To recall where we defined those check the below code:

add_settings_section('sunset-custom-options', 'Custom Theme Options', 'sunset_custom_options', 'sunset_option');
add_settings_field('sunset-name', 'First Name', 'sunset_option_name', 'sunset_option', 'sunset-custom-options');

And we are done, now go to the admin panel and go to the Sunset -> Theme Settings page, you will see an input field for first name. Write something and try saving it if everything is alright it will save the option data in the option table as first_name.

data-saved

If you go to the database and search for first_name in the wp_options table you will see the data is saved.

data-saved-db

Checkout the final code from this Gisthttps://gist.github.com/gomessimon/ec4b6bb4198f95b418d368fb99a6fc51

Simon Gomes

Comments ( 7 )
  1. Crystal88
    October 27, 2016 at 4:31 am
    Reply

    Reading your blog is pure pleasure for me, it deserves to go viral, you need some initial traffic only.

  2. Maruf
    December 13, 2016 at 8:05 pm
    Reply

    Very clear and concise. It was very helpful. Thanks a lot for sharing.

    • Simon Gomes
      December 14, 2016 at 7:35 am
      Reply

      Thank you too, I am glad.

  3. Sabbir saleh
    January 29, 2017 at 8:27 am
    Reply

    Thanks for sharing this.
    valuable and helpful.
    hopefully I will need this very soon.

    • Simon Gomes
      January 29, 2017 at 9:12 am
      Reply

      Thank you Sabbir, hope it will help you.

  4. beanerPn
    February 14, 2017 at 4:35 am
    Reply

    One more thing I would like to talk about is that instead of trying to match all your online degree tutorials on times that you end work (since the majority of people are exhausted when they return home), try to arrange most of your lessons on the week-ends and only one or two courses on weekdays, even if it means a little time off your weekend break. This is really good because on the saturdays and sundays, you will be much more rested as well as concentrated for school work. Thanks a lot for the different suggestions I have realized from your blog.

    • Simon Gomes
      February 14, 2017 at 6:00 am
      Reply

      Thanks for your advise. I will try to focus on that.

Leave a reply