Customizer Select List Control in WordPress : Dropdown

Used before category names. Blog WordPress WordPress Development

If you are developing WordPress theme, you will be deal with WordPress customizer. Customize WordPress theme is one of the options you can customize your theme based on your needs. To add customizer select list control, you can use below code.

In this post, we will give you a custom control makes it possible to add a select control to your theme customizer settings.

WordPress 3.4 introduced the Theme Customizer feature which allows site admins to tweak a theme’s settings and live preview those changes in real time.

The “control” can be loosely defined as “a reusable UI component” that can either be simple or more complex. WordPress itself provides some customizer controls that can be useful to develop customizer in less effort.

WordPress already provides a ‘select‘ control which displays a dropdown, and all you need to use it is an associative array of key-value pairs.

if (!function_exists('hs_customizer_register')) {
    function hs_zolog_footer_customizer_register($wp_customize)
    {
        $wp_customize->add_setting('hs_list', array(
            'capability' => 'edit_theme_options',
            'sanitize_callback' => 'hs_sanitize_select',
            'default' => '1',
        ));

        $wp_customize->add_control('hs_list', array(
            'type' => 'select',
            'section' => 'hs_section',
            'label' => esc_html__('Columns Count','text-domain'),
            'description' => esc_html__('Select columns count.','text-domain'),
            'settings' => 'hs_list',
            'choices' => array(
                '1' => esc_html__('1','text-domain'),
                '2' => esc_html__('2','text-domain'),
                '3' => esc_html__('3','text-domain'),
            ),
        ));
    }

    add_action('customize_register', 'hs_customizer_register');
}

if (!function_exists('hs_sanitize_select')) {
    function hs_sanitize_select($input, $setting)
    {
        $input = sanitize_key($input);
        $choices = $setting->manager->get_control($setting->id)->choices;
        return (array_key_exists($input, $choices) ? $input : $setting->default);
    }
}

In code above, we create a setting and control to display customizer select list control. The important part is sanitize_callback function. With this call back we tell WordPress that sanitize selected field by hs_sanitize_select which is our own custom sanitizer.

In hs_sanitize_select we took care of sanitization by our own function.

Tags: