我正在尝试在WordPress定制器的下拉列表中列出要使用的Google字体选项列表,但我无法正确使用此循环:
$i = 0;
foreach ($items as $font_value => $item) {
$i++;
$str = $item['family'];
}
上面的字符串需要位于下面数组中,以生成一个选项列表:
$wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'ounox-fonts-display-control', array(
'label' => 'Fonts Section',
'section' => 'ounox-fonts-section',
'settings' => 'ounox-fonts-display',
'type' => 'select',
'choices' => $str
)));
答案 0 :(得分:2)
foreach
循环不需要计数器,因此$i
是多余的。
每次迭代时你也会覆盖$str
。
$str = '';
foreach ($items as $font_value => $item) {
$str .= $item['family']; // . '##' in case you need a delimiter
}
答案 1 :(得分:1)
choices
参数expects an array,而不是字符串,因此您需要将每个$item['family']
保存到数组中,然后将该数组添加到参数中。
Hapstyx指出你不需要$i++
来迭代你的循环也是正确的。
choices
期望下拉选项的数组应如下所示:
$choices = array(
'option-value-1' => 'Option Title 1',
'option-value-2' => 'Option Title 2',
'option-value-3' => 'Option Title 3'
);
我们可以像这样构建这种类型的数组:
//predefine a blank array which we will fill with your options
$choices = array();
//loop through your items and that the values to the $choices array
foreach ($items as $font_value => $item) {
$choices[$item['slug']] = $item['family']; //I'm assuming your $item array contains some sort of slug to set as the value, otherwise, comment the above out, and uncomment the below:
// $choices[$item['family']] = $item['family']
}
//set your arguments
$args = array(
'label' => 'Fonts Section',
'section' => 'ounox-fonts-section',
'settings' => 'ounox-fonts-display',
'type' => 'select',
'choices' => $choices
);
//add the control
$wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'ounox-fonts-display-control', $args));