【问题标题】:PHP foreach loop used in Wordpress wp_customize->add_controlWordpress 中使用的 PHP foreach 循环 wp_customize->add_control
【发布时间】:2018-11-23 01:34:57
【问题描述】:

我正在尝试列出要在 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
)));

【问题讨论】:

    标签: php wordpress foreach


    【解决方案1】:

    foreach 循环不需要计数器,因此$i 是多余的。 您还将在每次迭代中覆盖 $str

    $str = '';
    foreach ($items as $font_value => $item) {
        $str .= $item['family']; // . '##' in case you need a delimiter
    }
    

    【讨论】:

      【解决方案2】:

      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));
      

      【讨论】:

      • 非常感谢,人的工作就像一个魅力对不起我真的是后端的菜鸟。我真的很感激人!
      • @MarkAnthony 随时 :) 乐于提供帮助 :)
      猜你喜欢
      • 1970-01-01
      • 2016-09-26
      • 2012-07-19
      • 1970-01-01
      • 2013-04-26
      • 1970-01-01
      • 1970-01-01
      • 2019-03-26
      • 1970-01-01
      相关资源
      最近更新 更多