Fill out custom field with used coupon code WooCommerce

不羁岁月 提交于 2019-12-23 05:18:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!