【问题标题】:Set dynamic options array to woocommerce_form_field using a global variable使用全局变量将动态选项数组设置为 woocommerce_form_field
【发布时间】:2019-09-01 11:51:20
【问题描述】:

我正在尝试在 WooCommerce 中将 options 参数数组设置为 woocommerce_form_field()

这是我将数组动态添加到 $GLOBALS 的代码:

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

$GLOBALS['hariharis'] = $balbal;

所以我在woocommerce_form_field()options 参数中使用它:

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

所以这里我使用变量$GLOBALS['hariharis']woocommerce_form_field() 中动态传递options 参数,但是我收到了这个错误:

“警告:array_keys() 期望参数 1 为数组,在 " 中给出 null。

我做错了什么?任何帮助表示赞赏。

【问题讨论】:

    标签: php arrays wordpress woocommerce field


    【解决方案1】:

    第一个代码块有一些错误:

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

    变量$balbal需要先初始化为空数组。
    没有将键/值对数组设置为$GLOBALS['hariharis']

    替换为:

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

    假设$g_values['shipping_code']$g_values['shipping_name'] 存在并且不为空,它应该会更好地工作。

    【讨论】:

    • 好的,谢谢。我已经按照您所说的修复了代码并且它有效。但是当我点击单选按钮时,代码无法获取单选值,为什么?
    • 请看我的相关帖子,谢谢。 stackoverflow.com/questions/57751221/…
    猜你喜欢
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    • 2013-03-23
    • 2017-04-03
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    相关资源
    最近更新 更多