add_action( 'woocommerce_after_order_notes', 'custom_select_field_with_random_options', 10, 1 );
function custom_select_field_with_random_options( $checkout )
{
// Heading for form
echo '<h4>' . __("Custom Question Heading", "woocommerce") . '</h4>';
$questions = array(
'1' => array(
'label' => __("one", "woocommerce"),
'options' => array(
'value1' => __("Choice 1.1", "woocommerce"),
'value2' => __("Choice 1.2", "woocommerce"),
),
),
'2' => array(
'label' => __("two", "woocommerce"),
'options' => array(
'value1' => __("Choice 2.1", "woocommerce"),
'value2' => __("Choice 2.2", "woocommerce"),
),
),
'3' => array(
'label' => __("three", "woocommerce"),
'options' => array(
'value1' => __("Choice 3.1", "woocommerce"),
'value2' => __("Choice 3.2", "woocommerce"),
),
),
);
$key = array_rand($questions); // Random key
$question = $questions[$key]; // The question data array
$label = $question['label'];
$default = array( '' => __("Choose an answer", "woocommerce") );
$options = $default + $question['options'];
woocommerce_form_field( 'question_'.$key, array(
'type' => 'select',
'class' => array( 'custom-dev-select'),
'label' => __("This is the question", "woocommerce") . ' ' . $label,
'options' => $options,
'required' => true
), $checkout->get_value( 'question_'.$key ) );
echo '<input type="hidden" name="question_key" value="'.$key.'">';
}
// Custom Checkout fields validation
add_action('woocommerce_checkout_process', 'custom_checkout_select_field_validation');
function custom_checkout_select_field_validation() {
if ( isset($_POST['question_key']) ) {
$key = esc_attr( $_POST['question_key'] );
if ( isset($_POST['question_'.$key]) && empty($_POST['question_'.$key]) )
wc_add_notice( '<strong>'. __("Please select a value", "woocommerce") . '</strong>', 'error' );
}
}
// Save custom checkout fields the data to the order
add_action( 'woocommerce_checkout_create_order', 'custom_checkout_field_update_meta', 10, 2 );
function custom_checkout_field_update_meta( $order, $data ){
if ( isset($_POST['question_key']) ) {
$key = esc_attr( $_POST['question_key'] );
if ( isset($_POST['question_'.$key]) && ! empty($_POST['question_'.$key]) ) {
$order->update_meta_data( '_question_value', esc_attr( $_POST['question_'.$key] ) );
$order->update_meta_data( '_question_key', $key );
}
}
}
// display the random question data in the order admin panel
add_action( 'woocommerce_admin_order_data_after_order_details', 'display_question_to_admin_order', 10, 1 );
function display_question_to_admin_order( $order ){
if( $key = $order->get_meta( '_question_key' ) ) {
if( $value = $order->get_meta( '_question_value' ) ) {
echo '<br style="clear:both">
<p><strong>' . __( "Random question", "woocommerce" ) . ' '. $key . ':</strong> ' . $value . '</p>';
}
}
}
代码进入活动子主题(活动主题)的function.php文件。测试和工作。