As a Theme Developer/Designer, you must always be thinking about what additional you can provide to your customers or clients. Well, the answer is  Custom Theme Options! Yes, you can customize your theme with WordPress Settings API which helps users with options to seamlessly modify its appearance. This is what you need right now and stay ahead in the game.

So, if you want to create a WordPress theme with a wide reach and large user base you can easily do so with WordPress settings API. The main requirement then is to create a professional, flexible and customizable theme.  Often when you build WordPress themes, they come with a Theme settings page, which can be used to modify the style and appearance.  This page allows taking user inputs like social media handles, custom logos, homepage layout etc. There are options on the settings page to customise theme features, behaviour and styles.

Notably, having these options makes it easier for novice users to make important changes, or modify the appearance without any coding skills. Since Theme Options are enhancements to a WordPress theme, they require additional code to be added to the theme. So WordPress developers can easily add custom theme options with the help of WordPress Settings API. The Settings API is a great option for developers who want to add more functionality through the custom theme options.

So, in this tutorial, we are going to discuss in detail about WordPress Settings API and how theme developers can use them for adding theme options to a page.

WordPress Settings API: Creating Custom Theme Options

The Settings API was added back in the WordPress 2.7 version. And it allows the developers to create admin pages, and define or choose what options they want to add to the theme settings. Also, they can provide users with the functionalities to change theme features. The developers can easily modify its “function.php” file, and easily add a custom WordPress theme options page to any theme. Remember the theme options depend upon the features and customization the theme supports. But there are a few common options that you can find on almost every theme settings page. Such as layout options, header logo, social URLs, and so on.

Benefits of Custom Theme Options

As a developer you can also choose not use the settings API. Instead you may opt to create your own admin panel from the scratch. However, if you use the settings APi there are a few advantages you get.  The primary benefits that the custom theme options offer are:

  • Easy customization for your theme: Users do not need to get into the details of directly editing the PHP or CSS files.
  • Customization capabilities for a WordPress theme: This increases the theme’s extensibility, flexibility, usability, and ease of operation. Users can modify the theme’s appearance with easy to use theme options.
  • Rise in Customer Satisfaction: By adding theme options for customising themes, a developer can please his customer to create a website that he desires. This leads to increase in overall customer satisfaction and theme usability from customer point-of-view.
  • Keeping up with the Trends in Web Designing: Theme options help developers to provide customizations that work with the trends. Like in today’s scenario, SEO and social media sharing options are primary components of a website. Custom WordPress theme options can help integrate differently styled social media options. With added SEO options to the theme, users will not need to worry about the search engine optimisation of every WordPress blog post.

 

WordPress Settings API

The WordPress Settings API is one of the most popular WordPress APIs. The Settings API allows admin pages to have fields for customising the way the WordPress theme works. The Settings API is a set of functions to support adding Custom Menus, WordPress Theme options and other Option Pages for themes. These also include API for saving, validating, and retrieving values from user input. Theme developers can use the API to add more powerful and interactive options to their themes.

Benefits of using WordPress Settings API for Theme Customization

Settings API is a convenient and secure method to add WordPress theme options and validating user inputs. The Settings API is a complete package that handles all aspects of adding admin options in WordPress. Using the Settings API involves some coding effort for the developers. However, they no longer need to work on complex debugging of the options management framework. Using the Settings API is not mandatory. Developers can still write their settings page without using this API. Nevertheless, the Settings API offers developers with several benefits that cannot be overlooked:

  • Visual Consistency with WordPress UI: The settings page would look like other administrative content.
  • Less bloat: Since the code is already available, it requires less coding to create a new admin panel.
  • Ease of Use for developers: The WordPress API adds lots of inbuilt support like for handling retrieving and storing of settings data.
  • WordPress hardened security with extra security measures: WordPress developers get access to secure methods of sanitizing data.
  • Robustness for the website: The API code is well tested and maintained making it more stable.
  • Compatibility with WordPress Core: This provisions that any updates automatically handle the custom settings page.
  • The uniformity: Having admin panels that match the UI of the WordPress looks more user-friendly. Moreover, you do not have to update the WordPress design in case of an update.
  • Security: The settings API also provide additional security measures needed to ensure the data is is getting saved.

How WordPress Settings API Work?

The Settings API offer the developers with complete capabilities to customise the settings page. They can register new settings pages or modify existing settings pages and register new settings or fields. Let us look at the structure of a theme setting and how developers can create and add their own settings.

 

Components of a Theme Setting

A theme setting that is added to the customizer screen consists of three parts:

  1. Section is a collection of fields. There should be at least one field in every section on a page. You can add new sections to existing settings pages or create a whole new settings page.
  2. Fields are the individual settings that you want to provide users with control to modify the values.
  3. Settings are combinations of the fields and sections and are registered in the database. You need to register the setting after defining both Fields and Sections.

 

Adding Sections

Sections correspond to the settings that are added to the options page. These allow organizing the settings on the page.

API: add_settings_section – To define new settings sections for an admin page. Call this API from inside an initializer function in the functions.php file. In our samples, we define it inside the admin_init hook that is triggered before any other hook when a user accesses the admin area. You can use this API for as many sections that you need to define for your theme options.

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

Parameters

NameTypeRequired/OptionalDescription
idstringRequiredSlug-name for the section. It is used in the ‘id’ attribute of tags.
option_groupstringRequiredFormatted title of the section. It is shown as the heading for the section.
option_groupcallableRequiredFunction that displays content at the top of the section.
option_groupstringRequiredThe slug-name of the settings page to which the section belongs.

Return Value: void

Sample Code: The sample code demonstrates the use of this API to add a new section to the default “Reading” settings page. Place this code in your functions.php file for the theme.

Function test_custom_settings () {
add_settings_section (
'first_section', //section name for the section to add
'New Reading Settings', //section title visible on the page
'reading_section_description', //callback for section description
'Reading'//page to which section will be added.
);
}
//callback for displaying setting description
function reading_section_description () {
echo '<p>This is the new Reading section. </p>';
}
//admin hook defined in functions.php. This calls the above function at
// initialization time.
add_action('admin_init', 'test_custom_settings' );

 

Adding Fields to Sections

Settings Fields represent the WordPress Theme Options and are part of the sections. The settings fields show as part of a section inside a settings page.

API: add_settings_field – To add settings fields to section. After you define the theme section, call this API from inside an initializer function like the admin_init hook defined in the functions.php file. You can use this API for as many settings fields that you need to define for your section.

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

Parameters

NameTypeRequired/OptionalDescription
idstringRequiredID of the field
titlestringRequiredTitle of the field
callbackcallableRequiredFunction to display the setting
pagestringOptionalThe slug-name of the settings page where setting is displayed
sectionstringOptionalThe slug-name of the section of the settings page in which to show the option
argsarrayOptionalExtra arguments used when displaying the field

Note that this function takes as input the settings page slug and the section id to which the setting belongs.

Return Value: void

Sample Code: The sample code demonstrates the use of this API to add a new field to the “first_section” section of the ‘Reading’ page. Take note that the API is called from the test_custom_settings function defined earlier where we added the theme section named “first_section”.

Function test_custom_settings () {
add_settings_section (
'first_section', //section name for the section to add
'New Reading Settings', //section title visible on the page
'reading_section_description', //section description
'Reading'//page to which section will be added.
);

add_settings_field (
'first_field_option' //ID for the settings field to add
'TestField', //settings title visible on the page
'options_callback', //callback for displaying the settings field
'Reading', // settings page to where option is displayed
'first_section'// section id for parent section.
);
}
//callback for displaying setting description
function reading_section_description () {
echo '<p>This is the new Reading section. </p>';
}
//callback for displaying the setting field
function options_callback ($args){
echo '<p>This is the new Reading setting callback. </p>';
}
//admin hook defined in functions.php. This calls the above function at
// initialization time.
add_action('admin_init', 'test_custom_settings' );

 

Registering the Settings

All the settings which you set up here get stored in the options table under the key used in the register_settings () function.

API: register_setting – To Register Settings

register_setting (string $option_group, string $option_name, array $args = array ())

Parameters

NameTypeRequired/OptionalDescription
option_groupstringRequiredThe settings group name like “general”, “reading”.
option_namestringRequiredName of the option to sanitise and save.
argsarrayOptionalData used to describe the setting when registered.

Return Value: void

Note that with version 4.7.0 the “args” parameter can contain an array of values. Prior to this version update, the third argument was the sanitize_callback for specifying the callback function for sanitizing the option’s value. There are also some built-in php callbacks that you can use as the sanitize callback.

Sample code:

The sample code demonstrates the use of this API for registering a test setting to the ‘Reading’ page. Call this API from inside an initializer function like the admin_init hook defined in the functions.php file.

function register_test_setting() {
register_setting ( 'Reading', 'first_field_option');
}
add_action( 'admin_init', 'register_test_setting' );

 

Adding Settings to new Settings Page

We have looked at the Settings API used for adding custom settings to an existing page. We have also seen sample code to add a new setting to the ‘Reading’ page. Let us look at the API required to add and display new settings to a new theme page. Add the code to call these API to the page in functions.php file for the theme.

API: settings_fields – To display option_page fields for a settings page. Call this function from inside of the form tag for the options page.

settings_fields ($option_group)

Parameters

NameTypeRequired/OptionalDescription
option_groupstringRequiredA settings group name. This should match the group name used in the register_setting () API.

Return Value: void

Sample code:

The sample code demonstrates the use of this API in a new custom options page.

<?php
echo '<form method="post" action="options.php">';
settings_fields( 'first_fields_option' );
?>

 

API: do_settings_sections – To print out all settings sections added to a settings page.

do_settings_sections ($page)

Parameters:

NameTypeRequired/OptionalDescription
pagestringRequiredThe slug name of the page whose settings sections need to be output

The page id should match the page name used in add_settings_section ().

Return Value: (void)

Sample code:

The sample code demonstrates the use of this API for displaying the settings sections for a page.

<?php
echo '<form method="post" action="options.php">';
do_settings_sections( 'theme-options' );
?>

 

Adding Custom WordPress Theme Options with WordPress Settings API

There are two parts to adding new settings to a settings page: adding the option and registering those settings. The Options API allow creating, reading, updating and deleting WordPress options. The Settings API and the Options API work as a combination for defining custom WordPress Theme Options.

The settings in a group are present in the wp_options database table and can be retrieved for later use. The wp_options table stores the settings as key-value pairs in the database. A single key-value pair is used for a single option setting. It is recommended to use an array with a single key when the number of values is more.

There are two APIs primarily used for adding and retrieving custom theme options.

 

Adding a Theme Option

API: add_option – To add a named option/value pair to the options database table. It does nothing if the option already exists. Call this API from the functions.php admin_init hook where you have registered the setting using the register_setting API. Doing so will create an entry in the options database for the setting and its default value.

add_option (string $option, mixed $value, '', string $autoload)

Parameters

NameTypeRequired/OptionalDescription
optionstringRequiredName of the option to be added
valuemixedRequiredValue for this option name
deprecatedstringOptionalDeprecated with version 2.3
autoloadstringOptionalWhether auto loaded. Valid values yes or no

Return Value: Boolean – False if the option was not added and true if the option was added.

Sample code

The sample code demonstrates the use of this API for adding a test option.

add_option('first_test_option', '255' , '', 'yes');

 

Retrieving a Theme Option

API: get_option – Retrieves an option value based on an option name. Use this API to get the default option value saved in the database or the value entered by the user in the theme setting UI. Use this API when you want to take further action based on what the user has selected. This includes changing the theme layout, adding specific features to the theme etc.

get_option (string $option, mixed $default = false)

Parameters

NameTypeRequired/OptionalDescription
optionstringRequiredName of the option to be retrieved.
defaultmixedRequiredDefault value to return if the option does not exist.

Note that there must be a default defined for handling cases when the option does not exist.

Return Value: Boolean – False if the option does not exist or does not have a value.

Sample code

The sample code demonstrates the use of this API for retrieving the value of a test option. Include this code where you want to change the theme appearance based on what the user has selected for the theme option.

$value = get_option('first_test_option');

 

Using the WordPress Settings API to Create Custom Theme Options

Let us now look at how a developer can add a new Theme Option using the WordPress Settings API. We list the tasks and the corresponding APIs for adding a new checkbox Theme Option to a theme.

As a reference for creating a complete working example, we have also added the sample code for adding a new Menu item and page. You may change it as per requirement.

Step 1: Create a new Menu for WordPress Theme Options

Add new menu named “Theme Customization” under the Appearance Menu. The new menu opens the page “theme_options” defined in next step.

//add new menu for theme-options page with page callback theme-options-page.

add_theme_page("Theme Customization", "Theme Customization", "manage_options", "theme-options", "theme_option_page", null, 99);

Output Settings Page

adding menu in settings page wordpress settings api theme options

 

Step 2: Add Blank Page for new Menu

Add new blank page “theme_options” for the “Theme Customization” menu. The page title is “Custom Theme Options Page”.

//this function creates a simple page with title Custom Theme Options Page.
function theme_option_page() {
?>
<div class="wrap">
<h1>Custom Theme Options Page</h1>
<form method="post" action="options.php">
<?php
?>
</form>
</div>
<?php
}

Output settings page

adding page in theme options menu wordpress settings api theme options

 

Step 3: Add and display custom sections to new Page

Display the sections for the page. Call these APIs only after you have defined the settings and sections in the functions.php file.

function theme_option_page() {
?>
<div class="wrap">
<h1>Custom Theme Options Page</h1>
<form method="post" action="options.php">
<?php
// display all sections for theme-options page
do_settings_sections("theme-options");
submit_button();
?>
</form>
</div>
<?php
}
function theme_section_description(){
echo '<p>Theme Option Section</p>';
}
//admin-init hook to create settings section with title “New Theme Options Section”.
function test_theme_settings(){
add_settings_section( 'first_section', 'New Theme Options Section',
'theme_section_description','theme-options');
}
add_action('admin_init','test_theme_settings');

Output settings page

wordpress settings api theme options

 

Step 4: Add Settings Field to Section

Next, we add a settings field called “first_field_option” to the section. We also register the field and add the theme option to the options database.

function theme_option_page() {
?>
<div class="wrap">
<h1>Custom Theme Options Page</h1>
<form method="post" action="options.php">
<?php
// display settings field on theme-option page
settings_fields("theme-options-grp");

// display all sections for theme-options page
do_settings_sections("theme-options");
submit_button();
?>
</form>
</div>
<?php
}
function theme_section_description(){
echo '<p>Theme Option Section</p>';
}
function options_callback(){
echo '<p>This is the new Setting</p>';
}
function test_theme_settings(){
add_option('first_field_option',1);// add theme option to database
add_settings_section( 'first_section', 'New Theme Options Section',
'theme_section_description','theme-options');

add_settings_field('first_field_option','Test Settings Field','options_callback',
'theme-options','first_section');//add settings field to the section “first_section”
register_setting( 'theme-options-grp', 'first_field_option');
}
add_action('admin_init','test_theme_settings');

Output settings page

adding field to sections wordpress settings api theme options

 

Step 5: Retrieve the Settings Field value

Let us now see how to retrieve and use the value of the settings field option. We modify the settings field display callback to set the initial value of a checkbox field. We use the get_option API to retrieve the value of the option from the database.

$value = get_option('first_field_option');,

In the sample code below, the value of the checkbox is set according to the value saved in the database. If the user checks the checkbox and submits the changes, then next time when he opens the “Theme Customization” tab, the checkbox will be checked as per value saved in the database.

function theme_option_page() {
?>
<div class="wrap">
<h1>Custom Theme Options Page</h1>
<form method="post" action="options.php">
<?php
// display settings field on theme-option page
settings_fields("theme-options-grp");
// display all sections for theme-options page
do_settings_sections("theme-options");
submit_button();
?>
</form>
</div>
<?php}
function add_theme_menu_item() {
add_theme_page("Theme Customization", "Theme Customization", "manage_options", "theme-options", "theme_option_page", null, 99);}
add_action("admin_menu", "add_theme_menu_item");
function theme_section_description(){
echo '<p>Theme Option Section</p>';}
function options_callback(){
$options = get_option( 'first_field_option' );
echo '<input name="first_field_option" id="first_field_option" type="checkbox" value="1" class="code" ' . checked( 1, $options, false ) . ' /> Check for enabling custom help text.';
}
function test_theme_settings(){
add_option('first_field_option',1);// add theme option to database
add_settings_section( 'first_section', 'New Theme Options Section',
'theme_section_description','theme-options');
add_settings_field('first_field_option','Test Settings Field','options_callback',
'theme-options','first_section');//add settings field to the “first_section”
register_setting( 'theme-options-grp', 'first_field_option');
}
add_action('admin_init','test_theme_settings');

Output settings page

custom help text theme options

 

Sample Illustrations Demonstrating Theme Options

The Settings API allows adding various types of settings to the Appearance Menu. Below we show two more examples for adding a text box setting and a file name input setting to the sample page.

 

Example 1: Add a Textbox for Reading Social URLs

We will modify the above code for adding an option to read the twitter handle of the user. Add below code to the function test_theme_settings function defined above in the functions.php file.

//add settings filed with callback display_test_twitter_element.
add_settings_field('twitter_url', 'Test Twitter Profile Url', 'display_test_twitter_element', 'theme-options', 'first_section');
register_setting( 'theme-options-grp', 'test_twitter_url');

Now add the callback for the settings field added.

function display_test_twitter_element(){
//php code to take input from text field for twitter URL.
?>
<input type="text" name="test_twitter_url" id="test_twitter_url" value="<?php echo get_option('test_twitter_url'); ?>" />
<?php
}

Output settings page

twitter theme options

 

Let us now see how the values can be used inside of the page display code. Let us assume we enter the URL “xyz.com” as the twitter URL in the setting “Test Twitter Profile URL” as shown below.


Now we need to use this value in our page display code. For our theme we add the code to the index.php file for the theme. You can add it in your theme with the code where you display the page. So, we add the following lines to the index.php inside the footer section of the page.

<footer id="colophon" class="site-footer"><div class="site-info">
// Retrieve the twitter url option from database.
<?php $twitter_url= get_option('test_twitter_url');?>
// Show the twitter URL in footer.
<?php _e('Twitter URL') ?> -<?php echo $twitter_url ?>
</div><!-- #page -->
<?php wp_footer(); ?></

When we load a page created in our theme we see that the footer shows the twitter URL “xyz.com” that we entered in our settings page.

 

Example 2: Add File Upload Option for Logo Image

We will now modify the above code for adding an option to get file name input for adding a logo file. Add below code to the function test_theme_settings defined above in the functions.php file.

//add settings filed with callback test_logo_display.
add_settings_field("logo", "Logo", "test_logo_display", "theme-options", "first_section");
register_setting( 'theme-options-grp', 'logo');

Now we define the callback for the settings field added.

function test_logo_display()
{
//php code to take input file name for logo image.
?>
<input type="file" name="test_logo" />
<?php echo get_option('test_logo'); ?>
<?php
}

Output settings page

logo theme options

You can use the get_option API to use the settings value for logo file and display the logo. The code would be similar to what is shown in the previous example.

 

Getting More with Settings API and WordPress Theme Options

The Settings API are easy to use and you can use them to create a customised settings page for your theme. It is important to plan the functionality you want to add to the page. You should also plan how you want to organize it on the settings page. You need to plan for the display options like Header, Footer etc. and the social options like Twitter, Facebook, Google Analytics etc. The Settings API provide you with the means to incorporate these custom theme options to your theme. The Settings API provide a lot of features but require a lot of coding effort and experience with coding and debugging. If you are a beginner and not too comfortable with all this code then you can skip all these coding steps by using the TemplateToaster software.

 

TemplateToaster for Creating Custom Theme Options and Themes

The TemplateToaster tool helps you make things work faster since TemplateToaster themes already have inbuilt theme options. The WordPress Settings API is already used in the TemplateToaster software. You do not need to manually configure the API for adding WordPress theme options. You can add these options directly in the theme as convenient options for the client. They can simply use these options from WordPress admin panel without any extra plugin or coding for these options.

In the Theme Options settings screen from TemplateToaster, we see that there are multiple categories of settings already supported. These include – header, Sidebar, Footer, Colours, SEO, Google Map etc.

Each option is further divided into sub-categories specific to the option. For the SEO options below, we see multiple sub-options like – SEO Enable, SEO General, and Web/Social etc.

If you need to add some more theme options, you don’t need to get into the details of the Settings API. Custom menus can be directly added as custom theme options for themes built with TemplateToaster, a WordPress website Builder and WordPress theme builder which allows you to directly add required function for the specific theme-options-menu section, in the theme’s functions.php file.

The options supported by TemplateToaster website maker are many and cover all the commonly used WordPress theme options. Novice developers and those working under strict time constraints can switch to using TemplateToaster tool for all their theme design needs.

Wrapping Up

In this post, we talked in detail about creating a custom WordPress setting page using the settings API. The WordPress options pages provide additional fields to the website users to clarify the entire website settings. In this guide, we talked in detail about WordPress settings and helped you how to create custom options pages in WordPress and more. Notably, using TemplateToaster WordPress theme builder can help you easily add needful functions to specific custom theme options, in the “functions.php file” of the theme.
Hopefully, now you will be able to easily create custom theme options with the help of WordPress settings API.