-2

I would like to store UTM parameters to Woocommerce order information (metabox). So I need to capture this during the checkout proces. Is there any code snippet available which achieves this?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Alex C
  • 1
  • 1

1 Answers1

0

Just a sample code below to get started. This is the steps required:

  1. Get javascript to write UTM parameters into cookies upon user visits or you can use PHP SESSION.
  2. Get PHP to read cookies/session and save the cookie values into the order meta during the woocommerce_checkout_update_order_meta action.
  3. Display the order meta in the meta box during the add_meta_boxes action.
function afl_woocommerce_checkout_update_order_meta($order_id, $data){
  $utm_source = $_COOKIE['utm_source'];

  add_post_meta($order_id, 'utm_source', $utm_source);
}

add_meta_box(
  'afl-wc-utm-meta-box',
  'AFL WooCommerce UTM Tracker',
  'afl_action_order_meta_box_display',
  'shop_order',
  'side',
  'low'
);

function afl_action_order_meta_box_display(){
  global $post;

  if (!empty($post->ID)) {
 
   $utm_source = get_post_meta($post->ID, 'utm_source', true);
   echo 'UTM Source: ' . $utm_source;
  }
}

References:

https://github.com/js-cookie/js-cookie

https://developer.wordpress.org/reference/functions/add_meta_box/

https://docs.woocommerce.com/wc-apidocs/source-class-WC_Checkout.html#400

Louis
  • 29
  • 2