Using the WordPress Settings API to Build a Custom Admin Page
In this guide, we’ll introduce the WordPress Settings API, and create a WordPress administration page where we demonstrate the use of this API.
For the purposes of this tutorial, we’ll wrap this functionality into a plugin, but this can also be a part of a WordPress theme.
As the WordPress Codex says, the Settings API was added in WordPress 2.7 to streamline adding different settings fields and sections in administration pages.
Key Takeaways
- The WordPress Settings API, introduced in WordPress 2.7, streamlines the process of adding different settings fields and sections in administration pages, and can be used to create a custom admin page.
- The process of creating a custom admin page involves creating and activating a plugin, creating an admin page, and using the Settings API to define and register settings, sections, and fields.
- The Settings API provides several functions, including register_setting() to register a setting, add_settings_section() to define/add a section to an admin page, and add_settings_field() to define a settings field within a settings section in an admin options page.
- The WordPress Settings API provides a standardized and secure way of handling data for themes and plugins, ensuring compatibility with WordPress core and making it easier for users to interact with settings without having to touch the code.
Creating the Plugin
To start, we’ll create and activate a plugin to encapsulate our options page. We’ll use WP CLI to simplify the creation, although this leaves us with way more files than this guide needs.
As we can see, we use wp scaffold plugin pluginname to create the plugin. Once it’s created, we activate it — optionally also using WP CLI, with wp plugin activate pluginname.
Once it’s activated, we open the main plugin file — in this case sitepoint-settings-api.php.
Creating the Admin Page
It isn’t necessary to use WP CLI for this plugin. We could have simply created a directory with the name of the plugin, and the PHP file inside it with the same name. Anyhow, the creation of the plugin has left us with a sitepoint-settings-api.php which looks like this:
<span><span><?php </span></span><span><span>/** </span></span><span><span> * Plugin Name: Sitepoint Settings Api </span></span><span><span> * Plugin URI: PLUGIN SITE HERE </span></span><span><span> * Description: PLUGIN DESCRIPTION HERE </span></span><span><span> * Author: YOUR NAME HERE </span></span><span><span> * Author URI: YOUR SITE HERE </span></span><span><span> * Text Domain: sitepoint-settings-api </span></span><span><span> * Domain Path: /languages </span></span><span><span> * Version: 0.1.0 </span></span><span><span> * </span></span><span><span> * <span>@package Sitepoint_Settings_Api </span></span></span><span><span> */ </span></span><span><span>~ </span></span>
Now we can simply add code after the comment end.
To add our options page, we’ll use add_options_page() (more details about it here). This function takes arguments as follows:
<span><span><?php </span></span><span><span>/** </span></span><span><span> * Plugin Name: Sitepoint Settings Api </span></span><span><span> * Plugin URI: PLUGIN SITE HERE </span></span><span><span> * Description: PLUGIN DESCRIPTION HERE </span></span><span><span> * Author: YOUR NAME HERE </span></span><span><span> * Author URI: YOUR SITE HERE </span></span><span><span> * Text Domain: sitepoint-settings-api </span></span><span><span> * Domain Path: /languages </span></span><span><span> * Version: 0.1.0 </span></span><span><span> * </span></span><span><span> * <span>@package Sitepoint_Settings_Api </span></span></span><span><span> */ </span></span><span><span>~ </span></span>
All the arguments are self-explanatory. $menu_slug must be a unique string that WordPress will use internally, but will also be reflected in the URL. $function is a string with a name of the function that will provide HTML output for our admin page.
We will, therefore, add the following code to our plugin file:
<span>add_options_page( $page_title, $menu_title, $capability, </span> <span>$menu_slug, $function ); </span>
After we’ve saved the file (presuming we activated our plugin), we’ll open our administration dashboard, and we’ll find our Settings API Page under Settings in the left side menu.
We can control, to a degree, the order or position of the submenu item by adding a priority argument to our add_action() function:
<span>add_action( 'admin_menu', 'sitepoint_settings_page' ); </span> <span>function sitepoint_settings_page() { </span> <span>add_options_page( 'Settings API Page', 'Settings API Page', 'manage_options', 'settings-api-page', 'settings_api_page' ); </span><span>} </span>
If we want to have our menu item to be in the root menu — rather than the Settings submenu — we’ll use add_menu_page(), which takes similar arguments.
Now, if we open the page in our browser, all we’ll see is an empty page, because we still haven’t created the settings_api_page() function that we specified:
The Settings API
The WordPress Settings API is an intricate mechanism that attempts to provide an easy way for developers to create settings pages.
Before we go into a full-fledged example of the settings page displaying and saving a setting to the WordPress database, we’ll explain couple of crucial functions that WordPress provides as part of its Settings API.
register_setting() is a function we use to register a setting, which equals a row in wp_options table. Before we can create actual field (or fields, as setting can be an array of values), we need to register it. This way we’ll leverage the WordPress CRUD mechanism for settings. Function arguments are as follows:
add_action( 'admin_menu', 'sitepoint_settings_page', 1 );
The first two arguments are mandatory, the first one allowing us to assign fields to it, and $option_name, as we’ll see, is the actual option name in the WordPress database.
add_settings_section() defines/adds a section to an admin page. Its arguments are as follows:
<span>register_setting( string $option_group, string $option_name, array $args = array() ) </span>
$callback is a function that outputs an HTL header of the section (it can be empty), and $page is the slug of the admin page we’ll display it on.
add_settings_field() defines a settings field within a settings section in an admin options page. Arguments for it are:
add_settings_section( string $id, string $title, callable $callback, string $page )
Of these, $id, $title, $callback and $page are required. The $callback function should output the HTML of the input field.
The Settings API provides $page argument for add_settings_section and add_settings_field as a means to add sections and fields to existing settings pages. We’ll use stpPlugin for both our option group — in register_setting() — and for attaching the settings section and settings fields to a ‘stpPlugin’ page in the add_settings_section() and add_settings_field() functions. We’ll then “quote it” in the next two functions in our example, to output relevant HTML.
settings_fields() outputs “nonce, action, and option_page fields for a settings page”. It takes the $option_group argument, used in register_setting().
do_settings_sections() outputs all the sections, with their respective fields, registered for a specific $page.
$page is the only argument here.
Having explained these functions, we now proceed to some actual code. The previous PHP code we added to the sitepoint-settings-api.php file we replace with the following:
<span><span><?php </span></span><span><span>/** </span></span><span><span> * Plugin Name: Sitepoint Settings Api </span></span><span><span> * Plugin URI: PLUGIN SITE HERE </span></span><span><span> * Description: PLUGIN DESCRIPTION HERE </span></span><span><span> * Author: YOUR NAME HERE </span></span><span><span> * Author URI: YOUR SITE HERE </span></span><span><span> * Text Domain: sitepoint-settings-api </span></span><span><span> * Domain Path: /languages </span></span><span><span> * Version: 0.1.0 </span></span><span><span> * </span></span><span><span> * <span>@package Sitepoint_Settings_Api </span></span></span><span><span> */ </span></span><span><span>~ </span></span>
Here we hook the stp_api_settings_init() function to the admin_init hook. There we define and register our settings, sections and fields.
stp_api_text_field_0_render() and stp_api_select_field_1_render() define HTML output of our two fields, text and select field, both belonging to the same stpPlugin group and stp_api_settings option — or setting — in the wp_options table in the database.
Lastly, we define stp_api_options_page(), which outputs the HTML for our admin options page. We incorporate the settings sections and fields in it. We’ve referred to this function at the top of our file, in the stp_api_add_admin_menu() function, where we registered the admin (options) page.
When we now go, again, to our settings page, we’ll see that it’s no longer empty:
If we try changing and saving these fields, we will see, upon refresh, that it works! WordPress abstracts away the database transactions for us, nonces, etc.
We could further add some validation functionality, further styling of this page, and other things.
If we go to WP CLI and try to run wp option get stp_api_settings — after we’ve changed some values for these two fields — we’ll get this:
This shows us that these two fields were saved in our wp_options database as fields of an array, as stp_api_settings setting.
If we now go to WP CLI shell, we can try out the code we’ll use to fetch these options in our plugin or theme files:
Conclusion
WordPress has become prominent in the web industry because of its ease of use and its gentle learning curve for developers. The Settings API is one example of this user-friendliness.
In this guide, we’ve introduced the WordPress Settings API. Much more can be said on this topic, but the intro we’ve presented here should demystify the topic to enable resourceful hackers to build their own solutions starting from this.
Frequently Asked Questions about WordPress Settings API
What is the WordPress Settings API and why is it important?
The WordPress Settings API is a set of functions and hooks provided by WordPress to help developers create, manage, and control options or settings on their WordPress sites. It is important because it provides a standardized and secure way of handling data for themes and plugins. It also ensures that your theme or plugin is compatible with WordPress core, making it easier for users to interact with your settings without having to touch the code.
How can I create a custom admin page using the WordPress Settings API?
Creating a custom admin page using the WordPress Settings API involves several steps. First, you need to register a new settings page using the add_menu_page() or add_submenu_page() function. Then, you need to define the settings fields using the add_settings_field() function. After that, you need to register the settings using the register_setting() function. Finally, you need to create a callback function to display the settings page.
How can I validate and sanitize data using the WordPress Settings API?
The WordPress Settings API provides a way to validate and sanitize data before it is saved to the database. This is done using the register_setting() function, which accepts a callback function as its third argument. This callback function is used to sanitize and validate the data. You can use WordPress’s built-in sanitization functions, or you can create your own custom sanitization function.
How can I add a settings section to a settings page?
You can add a settings section to a settings page using the add_settings_section() function. This function accepts three arguments: the ID of the section, the title of the section, and a callback function that displays the section. After creating the section, you can add fields to it using the add_settings_field() function.
How can I retrieve the value of a setting?
You can retrieve the value of a setting using the get_option() function. This function accepts the ID of the setting as its argument and returns the value of the setting. If the setting does not exist, it returns false.
How can I add a settings field to a settings section?
You can add a settings field to a settings section using the add_settings_field() function. This function accepts several arguments, including the ID of the field, the title of the field, a callback function that displays the field, the page on which the field should be displayed, and the section to which the field should be added.
How can I unregister a setting?
You can unregister a setting using the unregister_setting() function. This function accepts two arguments: the option group and the option name. After calling this function, the setting will no longer be registered and will not be displayed on the settings page.
How can I add a settings error to a settings page?
You can add a settings error to a settings page using the add_settings_error() function. This function accepts several arguments, including the ID of the setting, the title of the error, the message of the error, and the type of the error.
How can I display settings errors on a settings page?
You can display settings errors on a settings page using the settings_errors() function. This function accepts the ID of the setting as its argument and displays all errors associated with that setting.
How can I create a callback function for a settings field?
Creating a callback function for a settings field involves defining a new function that outputs the HTML for the field. This function should accept one argument, which is an array containing the arguments passed to the add_settings_field() function. Inside the function, you can use the get_option() function to retrieve the value of the field, and then output the HTML for the field.
The above is the detailed content of Using the WordPress Settings API to Build a Custom Admin Page. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

WordPressisgoodforvirtuallyanywebprojectduetoitsversatilityasaCMS.Itexcelsin:1)user-friendliness,allowingeasywebsitesetup;2)flexibilityandcustomizationwithnumerousthemesandplugins;3)SEOoptimization;and4)strongcommunitysupport,thoughusersmustmanageper

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo(); function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

Wix is suitable for users who have no programming experience, and WordPress is suitable for users who want more control and expansion capabilities. 1) Wix provides drag-and-drop editors and rich templates, making it easy to quickly build a website. 2) As an open source CMS, WordPress has a huge community and plug-in ecosystem, supporting in-depth customization and expansion.

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

WordPress itself is free, but it costs extra to use: 1. WordPress.com offers a package ranging from free to paid, with prices ranging from a few dollars per month to dozens of dollars; 2. WordPress.org requires purchasing a domain name (10-20 US dollars per year) and hosting services (5-50 US dollars per month); 3. Most plug-ins and themes are free, and the paid price ranges from tens to hundreds of dollars; by choosing the right hosting service, using plug-ins and themes reasonably, and regularly maintaining and optimizing, the cost of WordPress can be effectively controlled and optimized.
