Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 39 ยท Hooks, Templates and Settings

Adding Settings Pages and Tabs

Add your own tab to WooCommerce settings with WC_Settings_Page: register it, describe fields as arrays, use sections, then sanitize, validate and read the saved options.

Almost every extension needs some configuration: a threshold, an on/off switch, an API key, a message. WooCommerce already has a settings screen with tabs, sections and a consistent look, and it lets you add your own tab without writing any form markup or save code. You describe the fields as a PHP array, and the framework renders them, checks the nonce, sanitizes the values and stores them as options.

This lesson shows how the pieces fit together: a class that extends WC_Settings_Page, the filter that registers it, the array format for fields, sections inside a tab, how values are saved and read back, and where validation belongs. You have seen similar ideas in the general WordPress Settings API; the WooCommerce version is a thinner, array-driven layer on top of the same options table. Real WooCommerce code is read-only on this page. The two runnable examples are plain-PHP stand-ins that show how a field array becomes markup and how posted values become stored options.

The three parts of a settings tab

A tab has three jobs, and each one maps to a small piece of code:

  1. Register the tab so it appears in the tab bar.
  2. Describe the fields (and optionally sections) as arrays.
  3. Save the posted values. The base class does this for you when your fields use standard types.

The registration happens in a filter named woocommerce_get_settings_pages. It receives the list of settings page objects and returns it, with yours added. That filter is called on the WooCommerce settings screen, so you do not have to load your class on the front end at all.

PHP
<?php
// Read-only: registering a tab.
add_filter( 'woocommerce_get_settings_pages', function ( array $settings ): array {
    $settings[] = new Acme_Settings_Page();
    return $settings;
} );

Because WC_Settings_Page only exists once WooCommerce has loaded, define your class in a file that you include inside that filter callback (or after you have checked that WooCommerce is active, as in Your First WooCommerce Extension). A class that extends it at file load time will fatal if WooCommerce is missing.

The page class

The constructor sets an id, which becomes the tab slug and the prefix of several hooks, and a label, which is the visible tab name. Then it calls the parent constructor, which hooks the tab into the screen.

PHP
<?php
// Read-only: a settings tab with two sections.
class Acme_Settings_Page extends WC_Settings_Page {

    public function __construct() {
        $this->id    = 'acme';
        $this->label = __( 'Acme Notices', 'acme-notice' );
        parent::__construct();
    }

    /**
     * Fields of the default (first) section.
     *
     * @return array<int, array<string, mixed>>
     */
    protected function get_settings_for_default_section(): array {
        return array(
            array(
                'title' => __( 'Notice settings', 'acme-notice' ),
                'type'  => 'title',
                'desc'  => __( 'Control the banner shown above the cart.', 'acme-notice' ),
                'id'    => 'acme_notice_options',
            ),
            array(
                'title'   => __( 'Enable banner', 'acme-notice' ),
                'desc'    => __( 'Show the banner on the cart page', 'acme-notice' ),
                'id'      => 'acme_notice_enabled',
                'type'    => 'checkbox',
                'default' => 'yes',
            ),
            array(
                'title'    => __( 'Free shipping from', 'acme-notice' ),
                'desc_tip' => __( 'Order total in the store currency. Use 0 to hide the notice.', 'acme-notice' ),
                'id'       => 'acme_notice_threshold',
                'type'     => 'number',
                'default'  => '50',
                'css'      => 'width: 100px;',
                'custom_attributes' => array( 'min' => '0', 'step' => '1' ),
            ),
            array(
                'type' => 'sectionend',
                'id'   => 'acme_notice_options',
            ),
        );
    }
}

Recent WooCommerce versions let a page define one method per section (get_settings_for_default_section(), or get_settings_for_{$section}_section() for others) and take care of the rest. Older code, and a lot of code you will read in the wild, overrides get_settings() and get_sections() instead and switches on $current_section. Both styles work with the same field array format, which is the part worth learning well. Check the method names against the WooCommerce version you target, as the section methods have been refined over the years.

The field array format

Every setting is one array. The type key decides the control. The keys you use most often:

Key Meaning
type title, sectionend, text, number, email, password, textarea, checkbox, select, multiselect, radio, single_select_page, single_select_country and more
id The option name. This is the key you pass to get_option()
title The label in the left column
desc Description text. For a checkbox it appears next to the box
desc_tip A short help text shown as a tooltip
default Shown when the option does not exist yet. Also what get_option( $id, $default ) should use in your own code
options For select, multiselect and radio: an array of value to label
css, class Styling hooks for the input
custom_attributes Extra HTML attributes such as min, max, step, required
autoload Set to false for large or rarely used options, so they are not loaded on every request

Two types are not inputs. title opens a group with a heading and optional description, and sectionend closes it. Always give both the same id, and always close what you open, because the page output breaks otherwise.

flowchart LR
    A["Field arrays<br/>(id, type, default)"] --> B["WC_Admin_Settings::output_fields()"]
    B --> C["HTML form with nonce"]
    C -->|"Save changes"| D["WC_Admin_Settings::save_fields()"]
    D --> E["Sanitize by type"]
    E --> F["update_option(id, value)"]
    F --> G["get_option(id) in your code"]

From field array to stored option: the framework renders, checks, sanitizes and saves.

What the framework saves for you

When an administrator clicks "Save changes", the settings screen verifies a nonce and the manage_woocommerce capability, then WC_Admin_Settings::save_fields() walks your array. For each field that has an id, it reads the posted value and cleans it by type:

  • Checkboxes become yes or no (not true and false).
  • Textareas are passed through wp_kses_post, so basic HTML is kept.
  • Most other types go through wc_clean, which strips tags and trims.
  • Values for select-style fields are accepted as posted, so validate them against your options if the value matters.

Then it calls update_option(). Two consequences follow. First, an option is just a row in the options table; read it with get_option( 'acme_notice_threshold', '50' ) anywhere. Second, everything comes back as a string, including numbers and the checkbox yes/no. Cast and compare accordingly.

PHP
<?php
// Read-only: reading settings in your feature code.
function acme_notice_should_show( float $cart_total ): bool {
    if ( 'yes' !== get_option( 'acme_notice_enabled', 'yes' ) ) {
        return false;
    }
    $threshold = (float) get_option( 'acme_notice_threshold', '50' );
    return $threshold > 0 && $cart_total < $threshold;
}

A habit worth adopting is to wrap reads in one small function or class, so defaults and casting live in a single place, and the rest of the plugin never repeats option names.

Validation and custom sanitizing

The default cleaning is generic. If a threshold must not be negative, or a text must be a valid URL, add your own rule. WooCommerce passes each value through a filter named after the option, woocommerce_admin_settings_sanitize_option_{option_name}, before saving:

PHP
<?php
// Read-only: a stricter rule for one option.
add_filter( 'woocommerce_admin_settings_sanitize_option_acme_notice_threshold', function ( $value ) {
    $number = (float) $value;
    if ( $number < 0 ) {
        WC_Admin_Settings::add_error( __( 'The threshold cannot be negative.', 'acme-notice' ) );
        return get_option( 'acme_notice_threshold', '50' ); // keep the old value
    }
    return (string) $number;
} );

WC_Admin_Settings::add_error() shows a red notice after the page reloads, and WC_Admin_Settings::add_message() a green one. Returning the previous value on bad input is a friendly pattern: the form saves, the rest of the page is kept and only the bad field is rejected. Remember that validation in the browser (min, required) is a convenience for the user, never a security measure. Data that arrives on the server is checked on the server.

Try it: render a field schema

The real renderer is WC_Admin_Settings::output_fields(). This stand-in has the same input (an array of fields) and produces similar markup, so you can see how title, sectionend and the input types interact. Note how every value is escaped before it reaches the output.

PHP Field array to form markup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The real function also prints descriptions, tooltips, row classes, and many more field types. What matters here is the contract: the id is both the form field name and the option name, the default fills in for a missing option, and everything is escaped.

Try it: save with sanitizing and validation

Now the other half. This stand-in has a posted array, field definitions, a type-based cleaner like save_fields(), a custom validator for one option, and an in-memory "options table". Run it and read the result carefully: the checkbox is absent from the post when unchecked, the bad threshold is rejected, and the selected style is checked against its allowed options.

PHP Sanitize, validate, save

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice the unchecked checkbox: browsers do not send it at all, so the saver treats "missing" as no. That is why WooCommerce stores yes and no strings rather than booleans.

Sections, defaults and good habits

A tab with many fields becomes hard to use. Split it into sections, which appear as a row of links under the tab title (General | Advanced | Emails). Each section has its own field list, and saving stores the fields of the section the administrator is looking at. Give each setting to exactly one section.

A few habits keep settings maintainable:

  • Prefix every option id with your plugin slug (acme_notice_). The options table is shared by the whole site.
  • Keep defaults in one place. Define them in the field array and also pass the same default to get_option() in your code, or better, read through one helper function.
  • Do not store secrets in plain, autoloaded options if you can avoid it. API keys can live in options, but never print them back into the form unmasked or write them to logs; see Development Environment and Tooling for masking.
  • Set autoload to false for large values, such as a long list of rules.
  • Use capability checks for any custom save handler. The built-in screen requires manage_woocommerce; custom admin-post handlers must check it too.
  • Do not build a custom form when the field array can describe it. Custom HTML needs its own nonce, escaping and saving, which are all things the framework gets right once.

For an individual payment gateway or shipping method you do not write a settings page like this. Those classes have their own form_fields array in the same format, which you will meet in Building a Payment Gateway and Custom Shipping Methods.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you make your own tab appear on the WooCommerce settings screen?

    The woocommerce_get_settings_pages filter collects settings page objects. Your subclass sets an id and label, and the base class hooks the tab into the screen.
  2. 2. A field array has 'id' => 'acme_notice_threshold'. What is that id used for?

    The id is the posted field name and the key in the options table, so get_option( 'acme_notice_threshold' ) reads what the screen saved.
  3. 3. A checkbox field is saved and later read with get_option(). What value do you compare against to know whether it is on?

    WooCommerce stores checkboxes as the strings 'yes' and 'no'. Comparing with a boolean would always give the wrong result.
  4. 4. A threshold must never be negative. Where is the best place to enforce that?

    Browser attributes are a convenience that anyone can bypass. The server-side sanitize filter runs before saving, and can reject the value and add an error notice.

Summary

  • A settings tab is a WC_Settings_Page subclass with an id and a label, registered by returning it from the woocommerce_get_settings_pages filter.
  • Fields are arrays; type chooses the control, id is the option name, and title and sectionend entries group fields.
  • The framework renders the form, checks the nonce and capability, cleans values by type and stores them with update_option().
  • Options come back as strings, and checkboxes are yes or no.
  • Add stricter rules with woocommerce_admin_settings_sanitize_option_{id} and report problems with WC_Admin_Settings::add_error().
  • Prefix option ids, split big tabs into sections, and read settings through one helper.

Next: CRUD Classes and Data Stores