Skip to content

Instantly share code, notes, and snippets.

@juniorthiesen
Last active May 13, 2020 15:46
Show Gist options
  • Save juniorthiesen/eab1351335063568a660780f7f8e5d7a to your computer and use it in GitHub Desktop.
Save juniorthiesen/eab1351335063568a660780f7f8e5d7a to your computer and use it in GitHub Desktop.
Get UTM Source
<?php
// Set cookie for new users
add_action( 'init', 'set_newuser_cookie'); // Run when WordPress loads
function set_newuser_cookie() {
$cookie_value = $_SERVER["HTTP_REFERER"]; // Get URL the user came to your site for
if ( !is_admin() && !isset($_COOKIE['origin'])) { // If not an admin or if cookie doesn't exist already
setcookie( 'origin', $cookie_value, time()+3600*24*30, COOKIEPATH, COOKIE_DOMAIN, false); // Set cookie for 30 days
setcookie( 'utm_source', sanitize_key( $_GET['utm_source'] ), time() + ( 3 * 86400 ), COOKIEPATH, COOKIE_DOMAIN );
setcookie( 'utm_medium', $cookie_value, time()+3600*24*30, COOKIEPATH, COOKIE_DOMAIN, false); // Set cookie for 30 days
setcookie( 'utm_term', $cookie_value, time()+3600*24*30, COOKIEPATH, COOKIE_DOMAIN, false); // Set cookie for 30 days
}
}
// Check cookie when order made and add to order
add_action('woocommerce_checkout_update_order_meta', 'add_referral_meta'); // Run when an order is made in WooCommerce
function add_referral_meta( $order_id, $posted ){
$ref_url = $_COOKIE['origin']; // Get the cookie
$ref_utm_source = $_COOKIE['utm_source'];
$ref_utm_medium = $_COOKIE['utm_medium'];
$ref_utm_term = $_COOKIE['utm_term'];
update_post_meta( $order_id, 'utm_source' . sanitize_key( $_COOKIE['utm_source'] ), 1 );
update_post_meta( $order_id, 'referrer', $ref_url ); // Add to order meta
update_post_meta( $order_id, 'utm_source', $ref_utm_source ); // Add to order meta utm_source
update_post_meta( $order_id, 'utm_medium', $ref_utm_medium ); // Add to order meta utm_medium
update_post_meta( $order_id, 'utm_term', $ref_utm_term ); // Add to order meta utm_medium
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment