Aar*_*ruz 11 php forms wordpress multi-select woocommerce
我在WooCommerce的结帐页面添加了额外的字段,我可以添加基本字段,如文本框,但需要添加(多)选择框,用户可以在其中选择多个项目.我已经想出如何通过代码添加一个选择框,如下所示:
add_action('woocommerce_after_order_notes', 'my_custom_checkout_field');
function my_custom_checkout_field( $checkout ) {
echo '<div id="my_custom_checkout_field"><h3>'.__('My Field').'</h3>';
woocommerce_form_field( 'my_field_name', array(
'type' => 'select',
'class' => array('my-field-class form-row-wide'),
'label' => __('Fill in this field'),
'placeholder' => __('Enter something'),
'options' => array(
'Buick' => __('Buick', 'woocommerce' ),
'Ford' => __('Ford', 'woocommerce' )
)
), $checkout->get_value( 'my_field_name' ));
echo '</div>';
}
Run Code Online (Sandbox Code Playgroud)
但这只是一个选择下拉.
我可以为多选择做类似的事吗?
或者你有推荐的WooCommerce扩展吗?
请建议,提前谢谢!
您需要创建自己的自定义字段类型处理程序.如果您查看WooCommerce源代码,您将看到可以使用过滤器:'woocommerce_form_field_' . $args['type']
我还没有真正测试过这个,这只是单个"选择"控件的稍微修改过的代码,但是你明白了这一点:
add_filter( 'woocommerce_form_field_multiselect', 'custom_multiselect_handler', 10, 4 );
function custom_multiselect_handler( $field, $key, $args, $value ) {
$options = '';
if ( ! empty( $args['options'] ) ) {
foreach ( $args['options'] as $option_key => $option_text ) {
$options .= '<option value="' . $option_key . '" '. selected( $value, $option_key, false ) . '>' . $option_text .'</option>';
}
$field = '<p class="form-row ' . implode( ' ', $args['class'] ) .'" id="' . $key . '_field">
<label for="' . $key . '" class="' . implode( ' ', $args['label_class'] ) .'">' . $args['label']. $required . '</label>
<select name="' . $key . '" id="' . $key . '" class="select" multiple="multiple">
' . $options . '
</select>
</p>' . $after;
}
return $field;
}
Run Code Online (Sandbox Code Playgroud)
在您的代码中,只需将类型声明为"multiselect":
add_action('woocommerce_after_order_notes', 'my_custom_checkout_field');
function my_custom_checkout_field( $checkout ) {
echo '<div id="my_custom_checkout_field"><h3>'.__('My Field').'</h3>';
woocommerce_form_field( 'my_field_name', array(
'type' => 'multiselect',
'class' => array('my-field-class form-row-wide'),
'label' => __('Fill in this field'),
'placeholder' => __('Enter something'),
'options' => array(
'Buick' => __('Buick', 'woocommerce' ),
'Ford' => __('Ford', 'woocommerce' )
)
), $checkout->get_value( 'my_field_name' ));
echo '</div>';
}
Run Code Online (Sandbox Code Playgroud)