0

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?

1
  • I'm not a Wordpress user/developer, but you can use get_field() which returns array instead of get_field_object() and retyping that. advancedcustomfields.com/resources/get_field. Is it what you're looking for? Commented Apr 16, 2018 at 22:18

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

How to add in $cart_item['pick_up_list'] = explode('_', $pick_up_list[0]);.. show error array.
1

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

1 Comment

but no take [price] in options :/

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.