Reputation: 201
In woocommerce, I am trying to get the data from a multidimensional array from an Advanced custom field (ACF) to populate woocommerce_form_field()
select field options.
If I print_r
the data from:
$pickup = get_field_object('pick_up', 'pick_up_list')['value'];
I have this:
Array
(
[0] => Array
(
[name] => Hotel Cla
[price] => 0
)
[1] => Array
(
[name] => Ritz Carlon
[price] => 7
)
)
Then I'm getting the error Array to string conversion in
when using this array in:
woocommerce_form_field( 'pick_up_list', array(
'type' => 'select',
'class' => array('form-row-wide'),
'label' => __('Pick Up'),
'options' => $pickup
));
What I want is to be able to add the $pickup
array as select field. Any help?
Upvotes: 0
Views: 1162
Reputation: 253921
it can be also done in a simple FOR
loop, keeping both 'name'
and 'price'
values as <option>
submitted value:
$pickup = get_field_object('pick_up', 'pick_up_list')['value'];
$options = array();
for( $i = 0; $i < count($pickup); $i++ ){
$options[$pickup[$i]['name'].'_'.$pickup[$i]['price']] = $pickup[$i]['name'];
}
woocommerce_form_field( 'pick_up_list', array(
'type' => 'select',
'class' => array('form-row-wide'),
'label' => __('Pick Up'),
'options' => $options
));
Then once the data will be submitted, you will get it both 'name'
and 'price'
this way:
if( isset($_POST['pick_up_list']) ){
$pick_up_list = sanitize_text_field($_POST['pick_up_list']);
$pick_up_list = explode('_', $pick_up_list); // Separate the merged data
$name = $pick_up_list[0]; // The hotel name
$price = $pick_up_list[1]; // The hotel price
}
Upvotes: 1
Reputation: 1757
options should be an associative array key => value, try this:
$options = array();
foreach($pickup as $index => $values) {
$options[$index] = $values['name'];
}
Then, call the function:
woocommerce_form_field( 'pick_up_list', array(
'type' => 'select',
'class' => array('form-row-wide'),
'label' => __('Pick Up'),
'options' => $options
));
Upvotes: 1