问题
Right now I'm working with a mailchimp plugin that needs a custom field for validating/segmenting.
For this segment I want to check what kind of coupon is used. So I scavenged the following code that should fill my custom field with the used coupons:
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 ( empty( $_POST['my_field_name'] ) ) {
$coupons = $order->get_used_coupons();
update_post_meta( $order_id, 'my_field_name', $coupons);
}
}
Sadly this will only crash my site.
Any help would be greatly appreciated.
回答1:
There are several problems with your code:
- You're not validating if the field has any information, so you need
to check if
$_POST
has the my_field_name key - You need to load the
$order
variable in order to get the used coupons. - What happens when there's a my_field_value? Do you store it?
Here's the modified code:
add_action( 'woocommerce_checkout_update_order_meta',
'my_custom_checkout_field_update_order_meta' );
function my_custom_checkout_field_update_order_meta( $order_id, $posted ) {
if ( isset($_POST['my_field_name']) && empty( $_POST['my_field_name'])) {
$order = new WC_Order( $order_id );
$coupons = $order->get_used_coupons();
update_post_meta( $order_id, 'my_field_name', $coupons);
}
}
来源:https://stackoverflow.com/questions/35748925/fill-out-custom-field-with-used-coupon-code-woocommerce