Switch

Description

The switch field type creates a toggle switch input in the admin panel, allowing users to enable or disable a setting. It is rendered as a checkbox styled as a switch using Bootstrap’s form-switch component. This field is ideal for binary options (e.g., on/off, true/false).

Available Options

Parameter Type Description Required Default
name String The name of the field, used as the identifier and default label if label is not provided. Yes –
type String The field type. Must be set to switch. Yes –
label String The display label for the switch. If not provided, the name is used. No name
default Boolean/String The default state of the switch. Use true for checked or false for unchecked. Can also accept "checked" as a string. No false
class String Additional CSS classes to apply to the switch input for custom styling or JavaScript targeting. No –
help String A help message displayed in a sidebar or tooltip when the user clicks the info icon next to the field. No –


Note:
The switch field is stored in the settings array as a boolean-like value. The saved value is either the sanitized input (typically on for checked) or an empty string if unchecked.

Example

Below is an example of how to define a switch field in the $fields array for the Reusable Admin Panel settings class.

$this->fields = array(
    'general' => array(
        array(
            'name'        => __('Enabled', 'your-plugin-slug'),
            'type'        => 'switch',
            'label'       => __('Enable Feature', 'your-plugin-slug'),
            'default'     => false,
            'class'       => 'feature-toggle',
            'help'        => __('Toggle to enable or disable the feature.', 'your-plugin-slug')
        )
    )
);

This configuration will create a switch labeled “Enable Feature” under the “general” section. It will be unchecked by default, have the CSS class feature-toggle, and include a help message.

Usage Notes

  • The switch field uses WordPress’s sanitize_text_field for sanitization, ensuring the input is safe for storage.
  • The field’s ID is automatically generated as {section}-{name}, where name is sanitized using sanitize_title.
  • The switch is styled using Bootstrap’s form-switch class, and custom styles can be applied via the class parameter.
  • To retrieve the value of a switch field, use the get_option method, e.g., $this->get_option('general', 'enabled').