【发布时间】:2019-05-26 01:50:59
【问题描述】:
我正在使用 WordPress 5.0.2 和 WooCommerce 3.5.3,并且我在结帐页面上有一个带有 optgroup 的自定义选择下拉字段,该字段按预期工作,但它出现在订单备注之后,我希望它出现在billing_country 字段。
add_action('woocommerce_before_order_notes', 'custom_checkout_select_field_with_optgroup', 10, 1 );
function custom_checkout_select_field_with_optgroup( $checkout ) {
$domain = 'woocommerce';
$title = __("Region", $domain);
$slug = sanitize_title($title);
$default = __("Select your region", $domain);
$value = $checkout->get_value($slug);
// Region option data array with optgroup
$options = array(
__("North Region", $domain) => array(
'region1' => __("Region 1", $domain),
'region2' => __("Region 2", $domain),
),
__("South Region", $domain) => array(
'region3' => __("Region 3", $domain),
'region4' => __("Region 4", $domain),
)
);
// The field
echo '<p class="form-row form-row-wide '.$slug.'-dropdown" id="'.$slug.'_field" data-priority="">
<label for="'.$slug.'" class="">'.$title.'</label>
<span class="woocommerce-input-wrapper">
<select name="'.$slug.'" id="'.$slug.'" class="select " data-placeholder="" autocomplete="'.$slug.'">
<option value="">'.$default.'</option>';
// Loop through "optgroup"
foreach( $options as $optgroup_label => $optgroup_options ) {
echo '<optgroup label="'.$optgroup_label.'">';
// Loop through "options" in the "optgroup"
foreach( $optgroup_options as $key => $label ) {
$selected = $value === $key ? ' selected="selected"': '';
echo '<option value="'.$key.'"'.$selected.'>'.$label.'</option>';
}
echo '</optgroup>';
}
echo '</select></span></p>';
}
代码来自上一个帖子:WooCommerce Select Dropdown With Optgroup On Checkout
我知道这个自定义字段没有与woocommerce_checkout_fields 挂钩,如果我这样做,它不会显示该字段,因为我猜这个自定义选择字段不是从class-wc-countries.php 中提取的。
【问题讨论】:
标签: php wordpress select woocommerce checkout