Switch

The Switch controller allows users to switch between on and off states, and can also set an appropriate label for each state.

Demonstration

 
Handy::control( 'switches', [
    'id'          => 'switches_id',
    'section'     => 'layout_section',
    'label'       => esc_html__( 'Switch Control', 'textdomain' ),
    'description' => esc_html__( 'Description Here', 'textdomain' ),
    'priority'    => 1
]);

TIP

Here's an example using the default parameter. Note the default value accepts only a boolean data type.

 
Handy::control( 'switches', [
    'id'          => 'switches_id',
    'section'     => 'layout_section',
    'default'     => true,
    'label'       => esc_html__( 'Switch Control', 'textdomain' ),
    'description' => esc_html__( 'Description Here', 'textdomain' ),
    'priority'    => 1
]);

TIP

Here's an example using the choices parameter. Note the choices value accepts only an array data type that contains two elements. The first element is on, which contains the on state label. And the last element is off, which contains the off state label.

 
Handy::control( 'switches', [
    'id'          => 'switches_id',
    'section'     => 'layout_section',
    'default'     => true,
    'label'       => esc_html__( 'Switch Control', 'textdomain' ),
    'description' => esc_html__( 'Description Here', 'textdomain' ),
    'priority'    => 1,
    'choices'     => [
        'on'  => 'Enable',
        'off' => 'Disable'
    ]
]);

Basic Usage

 
// Return a boolean.
$value = get_theme_mod( 'switches_id' );

Parameters

NameDescription
id

string required

The unique slug like string used as an ID and also as an index name in storing data in a database.

section

string required

The ID of the section in which the control will be displayed.

default

boolean optional

The predetermined value of the control. Default false.

choices

array optional

The switch's on/off state label. Default empty array.

  • on string optional

    The switch's on state label.

  • off string optional

    The switch's off state label.

label

string optional

The label or title of the control to show in the UI. Default empty.

description

string optional

The description of the control to show in the UI. Default empty.

priority

integer optional

The order of control appears in the section. Default 0.

validations

array optional

The set of validations used to validate the value of the control. For further details, read validations. Default empty.

active_callback

callable optional

A callback function that determines the visibility of a control, whether to show or hide depending on a condition. For further details, read active_callback. Default empty.

sanitize_callback

callable optional

A callback function that sanitizes the value of control before storing it in the database. Note that this is only optional since each control is already well sanitized. For further details, read sanitize_callback. Default empty.