【发布时间】:2020-03-24 19:41:59
【问题描述】:
在 WooCommerce 中,我使用在结帐页面上显示自定义字段的代码。填写此字段并由客户下订单后,数据将显示在“谢谢”页面,编辑订单时和电子邮件通知中。
// Add the delivery custom field to the checkout
add_action( 'woocommerce_before_order_notes', 'my_delivery_custom_checkout_field' );
function my_delivery_custom_checkout_field( $checkout ) {
echo '<div><h3>' . __('Custom Delivery') . '</h3>';
woocommerce_form_field( 'my_custom_delivery', array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'label' => __('My Custom Delivery'),
'placeholder' => __(''),
), $checkout->get_value( 'my_custom_delivery' ));
echo '</div>';
}
// Update the order meta with field value
add_action( 'woocommerce_checkout_update_order_meta', 'my_custom_delivery_checkout_field_update_order_meta' );
function my_custom_delivery_checkout_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST['my_custom_delivery'] ) ) {
update_post_meta( $order_id, 'my_custom_delivery', sanitize_text_field( $_POST['my_custom_delivery'] ) );
}
}
// Display custom delivery field value on the order edit page
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_delivery_checkout_field_display_admin_order_meta', 10, 1 );
function my_custom_delivery_checkout_field_display_admin_order_meta($order){
echo '<div><strong>'.__('Custom Delivery').':</strong> ' . get_post_meta( $order->id, 'my_custom_delivery', true ) . '</div>';
}
// Display custom delivery field in "Order received" and "Order view" pages (frontend)
add_action( 'woocommerce_order_details_after_order_table', 'my_custom_delivery_data_in_orders', 10 );
function my_custom_delivery_data_in_orders( $order ) {
$my_custom_delivery = $order->get_meta( 'my_custom_delivery' );
echo '<div><span>'.__('Custom Delivery').':</span> ' . $my_custom_delivery . '</div>';
}
// Display custom delivery field in Email notifications
add_filter( 'woocommerce_email_order_meta_fields', 'my_custom_delivery_data_in_emails', 10, 3 );
function my_custom_delivery_data_in_emails( $fields, $sent_to_admin, $order ) {
$fields['Custom Delivery'] = array(
'label' => __( 'Custom Delivery' ),
'value' => $order->get_meta( 'my_custom_delivery' ),
);
return $fields;
}
但有两个问题我想解决:
- “Custom Delivery”字段名称始终显示在订单编辑页面和电子邮件通知中,即使客户未填写此字段。
如果客户未填写该字段,我需要在这些页面上隐藏名称“Custom Delivery”。
- “Custom Delivery”字段的数据显示在订单数据表格的后面。
我需要在“谢谢”页面的订单表和电子邮件通知中显示该字段的数据。
我很乐意为您提供帮助!
【问题讨论】:
标签: php wordpress woocommerce checkout hook-woocommerce