如何通过WordPress定制API创建要迭代的值列表?

时间:2016-01-07 作者:davemackey

我目前有一个安装了OptionTree的主题。它用于创建位置列表,然后在页面标题的下拉列表中可见。OptionTree的显示代码如下所示:

<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 $listedlocation[link];?>"><?php echo $listedlocation[title];?></option>
            <?php endforeach;?>
        </select>
    </div>
</form>
我想使用WordPress自定义API将其转换为类似的内容,但我不确定如何实现这一点。我已经成功地实现了定制API,它只接受一个值,而不需要迭代多个值。

1 个回复
SO网友:cjbj

假设您有一个数组$locations 可用时,可以使用此代码在自定义程序中生成下拉列表。它与单个值没有什么不同。

$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));
道具Otto.