1

I am trying to set an array of options argument to woocommerce_form_field() in WooCommerce.

Here is my code that add dynamically an array to $GLOBALS:

foreach($kekei as $goods=> $goodness) { 
    $balbal."'".[$goodness['shipping_code']] = $goodness['shipping_name'];              
}

$GLOBALS['hariharis'] = $balbal;

So I use it in options argument in woocommerce_form_field():

add_action( 'woocommerce_review_order_after_shipping', 'custom_shipping_radio_button', 20);
$domain = 'woocommerce';

if (  WC()->session->get( 'chosen_shipping_methods' )[0] == targeted_shipping_method() ) :


echo '<tr class="delivery-radio"><th>' . __('Delivery options', $domain) . '</th><td>';

$chosen = WC()->session->get('chosen_delivery');
$chosen = empty($chosen) ? WC()->checkout->get_value('delivery') : $chosen;
$chosen = empty($chosen) ? 'regular' : $chosen;

// Add a custom checkbox field
woocommerce_form_field( 'radio_delivery', array(
    'type' => 'radio',
    'class' => array( 'form-row-wide' ),
    /*
    'options' => array(
    'regular' => __('Regular', $domain),
    'premium' => __('Premium +'.wc_price(2.00), $domain),
    'big' => __('Big +'.wc_price(3.00), $domain),
    'small' => __('Big +'.wc_price(5.00), $domain),

    */
    'options' => $GLOBALS['hariharis'],
    'default' => $chosen,
), $chosen );

echo '</td></tr>';

endif;
}

So here I use the variable $GLOBALS['hariharis'] to dynamically pass options argument in woocommerce_form_field(), but I am getting this error:

"Warning: array_keys() expects parameter 1 to be array, null given in ".

What I am doing wrong? Any help is appreciated.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399

1 Answers1

0

There are some mistakes in this first code block:

foreach($kekei as $goods=> $goodness) { 
    $balbal."'".[$goodness['shipping_code']] = $goodness['shipping_name'];
}

$GLOBALS['hariharis'] = $balbal;

The variable $balbal need to be initialized as an empty array first.
You are not setting an array of key/values pairs into $GLOBALS['hariharis'].

Replace it with:

// Initializing the variable
$balbal = array();

// Loop through your multidimensional array
foreach( $kekei as $g_key => $g_values ) { 
    // Set key/value pairs to the new array
    $balbal[ $g_values['shipping_code'] ] = $g_values['shipping_name'];
}

$GLOBALS['hariharis'] = (array) $balbal;

It should better work assuming that $g_values['shipping_code'] and $g_values['shipping_name'] exist and are not empty.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • ok, thank you. I have fixed the code by following what you said and it worked. But when i clicked on the radio button, the code cannot pickup the radio value, why? – spider aladin Sep 01 '19 at 21:54
  • please see my related thread, thank you. https://stackoverflow.com/questions/57751221/trying-to-ajax-woocommerce-form-field-but-have-null-error-at-console-log – spider aladin Sep 02 '19 at 03:53