How Can I Create a List of Values to Be Iterated Through via WordPress Customization API?

I currently have a theme with OptionTree installed. It is used to create a list of locations which are then visible in a dropdown in the header of the page. The display code with OptionTree looks like this:

<form action="" id="formsel" method="post">
    <div class="locations">
        <?php $location = ot_get_option('location');?>
        <label for="country_id" class="no-display">Select Country</label>
        <select name="country_id" id="country_id" tabindex="1">
            <option value="">Location</option>
            <?php foreach($location as $listedlocation):?>
                   <option value="<?php echo $listedlocationhttps://wordpress.stackexchange.com/questions/213980/how-can-i-create-a-list-of-values-to-be-iterated-through-via-wordpress-customiza;?>"><?php echo $listedlocationHow Can I Create a List of Values to Be Iterated Through via WordPress Customization API?;?></option>
            <?php endforeach;?>
        </select>
    </div>
</form>

I’d like to convert this into something similar using the WordPress Customization API, but I am unsure how to accomplish this. I have successfully implemented the customization API where it takes a single value, but not where it needs to iterate over a number of values.

1 Answer
1

Assuming you have an array $locations available, you can use this code to generate a dropdown in the customizer. It’s not that different from a single value.

$section_name="wpse213980_section_name"; // adapt to your naming system
$section_title="wpse213980_section_title"; // adapt to your naming system
$setting_name="wpse213980_setting_name"; // adapt to your naming system
$setting_field_type="select";
$setting_field_options = $locations;
$sanitize_callback = 'sanitize_text_field';

$wp_customize->add_setting($setting_name, array(
  'default'                 =>  '',
  'type'                    =>  'theme_mod',
  'capability'              =>  'edit_theme_options',
  'theme_supports'          =>  '',
  'transport'               =>  'refresh',
  'sanitize_callback'       =>  $sanitize_callback
   ));

$control_args = array(
    'section'                   =>  $section_name,
    'label'                     =>  $setting_title,
    'settings'                  =>  $setting_name,
    'priority'                  =>  10,
    'type'                      =>  $setting_field_type,
    'choices'                   =>  $setting_field_options,
    );

$wp_customize->add_control( new WP_Customize_Control ($wp_customize, $setting_name, $control_args));

Props Otto.

Leave a Comment