0

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.

Tristan .L
  • 829
  • 3
  • 9
  • 20
  • Can you add the PHP error? any log? – Skatox Mar 02 '16 at 14:01
  • I cannot, however I figured something out. changing: `$coupons = $order->get_used_coupons();` To: `$coupons = $order_id->get_used_coupons();` keeps it from crashing but will still not fill out my field. This is probably due the fact that $order was never defined. – Tristan .L Mar 02 '16 at 14:14

1 Answers1

0

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);
  }

}
Skatox
  • 4,237
  • 12
  • 42
  • 47
  • Okay your code kinda works, however it wil return 'array' as coupon field and the value is never displayed in the actual field on the front-end. Which is where I think i need it to be able to let my plugin check if the custom field contains certain coupon codes. – Tristan .L Mar 02 '16 at 14:29
  • by replacing `$coupons = $order->get_used_coupons();` with `foreach( $order->get_used_coupons() as $coupon) { $coupons .= $coupon.'\n'; }` I no longer get 'array' in my field but the actual coupon. So that part is solved.. – Tristan .L Mar 02 '16 at 15:09
  • Yes, you need to validate that as well. Also remember that you can store arrays in the post meta – Skatox Mar 02 '16 at 15:10
  • It's better to do explode($order->get_used_coupons(),'\n') that the foreach – Skatox Mar 02 '16 at 15:11
  • Thank you! The remaining problems I have, have nothing to do with the code but with the plugin it seems. Problem solved. – Tristan .L Mar 02 '16 at 15:24