我对解释从 woocommerce 获得的一段代码有疑问。该代码运行良好,但我在理解其中的某些部分时遇到了问题。
下面是代码:
* Adding the Custom field to the checkout
**/
add_action('woocommerce_after_order_notes', 'my_custom_checkout_field');
function my_custom_checkout_field( $checkout ) {
global $woocommerce;
$found = false;
//check if product already in cart
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == 209) {
echo '<div id="my_custom_checkout_field"><h3>'.__('My Field').'</h3>';
woocommerce_form_field( 'my_field_name', array(
'type' => 'checkbox',
'class' => array('my-field-class form-row-wide'),
'label' => __('Fill in this field'),
'placeholder' => __('Enter a number'),
), $checkout->get_value( 'my_field_name' ));
echo '</div>';
echo '<div id="my_custom_checkout_field2"><h3>'.__('Keywords').'</h3>';
woocommerce_form_field( 'enter_keywords', array(
'type' => 'text',
'required' => true,
'class' => array('my-field-class form-row-wide'),
'label' => __('Enter Keywords'),
'placeholder' => __('Enter something'),
), $checkout->get_value( 'keywords' ));
echo '</div>';
}
}
}
}
/**
* Update the order meta with field value
**/
add_action('woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta');
function my_custom_checkout_field_update_order_meta( $order_id ) {
if ($_POST['my_field_name']) update_post_meta( $order_id, 'My Field', esc_attr($_POST['my_field_name']));
if ($_POST['keywords']) update_post_meta( $order_id, 'Keywords', esc_attr($_POST['keywords']));
}
/**
* Add the field to order emails
**/
add_filter('woocommerce_email_order_meta_keys', 'my_custom_checkout_field_order_meta_keys');
function my_custom_checkout_field_order_meta_keys( $keys ) {
$keys[] = 'My Field';
$keys[] = 'Keywords';
return $keys;
}
/**
* Process the checkout
**/
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
global $woocommerce;
// Check if set, if its not set add an error.
if (!$_POST['enter_keywords'])
$woocommerce->add_error( __('Please enter keywords...') );
}
上面的代码与发送电子邮件有关。
我的疑问是:
Why should I give values for $keys[] as:
$keys[] = 'My Field';
$keys[] = 'Keywords';
为什么我不能给 my_field_name ,关键字作为值$keys[]
?
最重要的是这 3 个函数相互理解,如果我为 $keys[] 给出“我的字段”和“关键字”,那么只有我收到一封电子邮件,否则没有,那么为什么不能为 $keys[] 给出其他值?