WooCommerce中ACF多维数组填充下拉选项时遇数组转字符串错误
Got it, let's break down why you're hitting this error and how to fix it quickly.
The Root Cause
The woocommerce_form_field() function expects the options parameter to be a one-dimensional key-value array (like array('value1' => 'Label 1', 'value2' => 'Label 2')). But right now, you're passing a multidimensional array with nested name and price keys—PHP can't convert that nested array to a string for the dropdown options, hence the error.
Step-by-Step Solution
First, we need to transform your ACF multidimensional array into the flat key-value structure WooCommerce expects. Here's how to do it:
Fetch and validate your ACF data
First, make sure you're correctly retrieving the field data (we'll add a safety fallback too):// Get the ACF field object and its value $pickup_field = get_field_object('pick_up', 'pick_up_list'); $pickup_data = $pickup_field['value'] ?? array(); // Fallback to empty array if no data existsConvert the multidimensional array to valid dropdown options
Loop through the nested array and build a new flat array. You can even include the price in the label for customer clarity:// Initialize empty array for dropdown options $pickup_options = array(); // Only proceed if we have valid, non-empty data if (!empty($pickup_data) && is_array($pickup_data)) { foreach ($pickup_data as $location) { // Create a user-friendly label (e.g., "Hotel Cla (¥0)") $label = sprintf('%s (¥%d)', $location['name'], $location['price']); // Use a sanitized version of the name as the option key (unique and URL-friendly) $key = strtolower(str_replace(' ', '-', $location['name'])); // Add the key-label pair to our options array $pickup_options[$key] = $label; } }Render the WooCommerce select field
Now pass the transformed$pickup_optionstowoocommerce_form_field():woocommerce_form_field( 'pickup_location', // Unique field name for your form array( 'type' => 'select', 'class' => array('form-row-wide'), 'label' => 'Pickup Location', 'required' => true, 'options' => $pickup_options, // Use our converted array here ), '' // Optional: set a default selected value here );
Additional Notes
- If you don't want to display the price in the label, just use
$location['name']as both the key and label. - Using the sanitized name as the option key ensures uniqueness—critical for select fields to work properly.
- The
?? array()fallback prevents errors if your ACF field has no saved data yet.
内容的提问来源于stack exchange,提问作者Juan David

