WordPress Settings API Creating Theme Options and more Blog image

As a Theme Developer/Designer, Do you always think of what extra could be provided to your customers/clients? Custom Theme Options! Yes, Customize your theme with WordPress Settings API and empower users with options to quickly modify its appearance. This is what you need right now and stay ahead in the game.

Obviously, you want to create a WordPress theme with a widespread reach and large user base. The main requirement then is to create a professional, flexible and customizable theme. Most WordPress themes provide a Theme settings page to alter its appearance and style. This page allows taking user inputs like social media handles, custom logo, homepage layout etc. There are options in the settings page to customise theme features, behaviour and styles. These theme options help novice users to change the theme’s appearance without any coding effort. Since Theme Options are enhancements to a WordPress theme, they need additional code to be added to the theme. WordPress developers can add custom theme options by using the WordPress Settings API. The Settings API is an apt choice for developers to provide users with extra functionality through the custom theme options. In this tutorial, we will understand the WordPress Settings API and how theme developers can use them for adding theme options to a page.

 

WordPress Theme Options

The WordPress Theme Options screen provides appearance settings for a theme right from the dashboard. Developers can choose what options they want to add to their theme settings. They can provide the users with the capabilities to change theme features. Developers can add a WordPress theme options page to any theme simply by modifying it’s “functions.php” file. Theme options depend on the features and customization the theme supports. However, there are some common options present in every theme settings page. These include layout options, social URLs, header logo etc.

 

Benefits of Custom Theme Options

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 was added in WordPress 2.7 and 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 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.
  • 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 sanitising 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.

 

How 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 organising 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:

Name Type Required/Optional Description
id string Required Slug-name for the section. It is used in the ‘id’ attribute of tags.
option_group string Required Formatted title of the section. It is shown as the heading for the section.
option_group callable Required Function that displays content at the top of the section.
option_group string Required The 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:

Name Type Required/Optional Description
id string Required ID of the field
title string Required Title of the field
callback callable Required Function to display the setting
page string Optional The slug-name of the settings page where setting is displayed
section string Optional The slug-name of the section of the settings page in which to show the option
args array Optional Extra 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 setup 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:

Name Type Required/Optional Description
option_group string Required The settings group name like “general”, “reading”.
option_name string Required Name of the option to sanitise and save.
args array Optional Data 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 sanitising the option’s value. There are also some built-in php callbacks that you can use as the sanitise 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:

Name Type Required/Optional Description
option_group string Required A 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:

Name Type Required/Optional Description
page string Required The 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 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:

Name Type Required/Optional Description
option string Required Name of the option to be added
value mixed Required Value for this option name
deprecated string Optional Deprecated with version 2.3
autoload string Optional Whether 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:

Name Type Required/Optional Description
option string Required Name of the option to be retrieved.
default mixed Required Default 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 Settings API to Create Custom Theme Options

Let us now look at how a developer can add a new Theme Option using the 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 “http://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 “http://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 organise 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 in-built 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. You can directly add required function for the specific theme-options-menu section, in the theme’s functions.php file.

The options supported by TemplateToaster 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.