动态添加键值对到woocommerce checkout字段过滤器的options属性

时间:2017-03-21 09:06:59

标签: php wordpress woocommerce

我正在使用woocommerce_checkout_fields过滤器向woocommerce结帐添加一些自定义字段。其中一个字段是select下拉列表。这是我的字段代码。

// Add a new checkout field
function ds_filter_checkout_fields($fields){
    $suburb = ds_get_delivery_suburbs();
    $postcodes = ds_get_delivery_postcodes();
    $fields['extra_fields'] = array(
        'some_field' => array(
            'type' => 'text',
            'required'      => true,
            'label' => __( 'Some field' )
        ),
        'select_field' => array(
            'type' => 'select',
            'options' => array('key' => 'value'),
            'required'      => true,
            'label' => __( 'Another field' )
        )
    );

    return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'ds_filter_checkout_fields' );

如果您检查select_field代码,则存在options属性,它需要键和值对...我想将动态键和动态值插入options属性。在代码中,我从key获取动态$postcodes,从value获取动态$suburb,当我尝试按此'options' => array($postcodes => $suburb),插入时,我得到了这个警告Warning: Illegal offset type ...我尝试了其他几种方法,但它们没有用,所以我转向你们......我感谢你的帮助......期待你们的回应。

注意:我已经搜索了这个,但没有找到任何答案,所以我转向Stackoverflow寻求帮助。

1 个答案:

答案 0 :(得分:0)

如果你想要它是动态的,你必须首先设置并填充数组然后使用它,所以它将是

// Add a new checkout field
function ds_filter_checkout_fields($fields){
    $suburb = ds_get_delivery_suburbs();
    $postcodes = ds_get_delivery_postcodes();
    $ma_options[$postcodes] = $suburb; 
    $fields['extra_fields'] = array(
        'some_field' => array(
            'type' => 'text',
            'required'      => true,
            'label' => __( 'Some field' )
        ),
        'select_field' => array(
            'type' => 'select',
            'options' => $ma_options[$postcodes],
            'required'      => true,
            'label' => __( 'Another field' )
        )
    );

    return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'ds_filter_checkout_fields' );

如果它不起作用则分享var_dump($ ma_options);

---更新

这可能是因为索引不存在或者传递的东西不是字符串作为键。如果需要,应该将类型转换为字符串,或使用stdClass对象。