Skip to content

Instantly share code, notes, and snippets.

@stevenkellow
Created June 23, 2016 08:42
Show Gist options
  • Save stevenkellow/48cfc745d80d951b6840421a5c1033c3 to your computer and use it in GitHub Desktop.
Save stevenkellow/48cfc745d80d951b6840421a5c1033c3 to your computer and use it in GitHub Desktop.
Add Referrer to WooCommerce order
<?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
}
}
// 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
update_post_meta( $order_id, 'referrer', $ref_url ); // Add to order meta
}
@aiiddqd
Copy link

aiiddqd commented Dec 13, 2016

It's great. Very useful! Thx!

@Geert46
Copy link

Geert46 commented May 11, 2017

He Stevenkellow,

Awesome code and very useful thanks! However, can't get it to show the page BEFORE my url is entered. As in: this code shows the page the user was before buying a product, not before entering my site. What I need is to see where the user was before he visited my site.

For example, when a visitor comes from google.com to mysite.com i want it to show google.com. Now it outputs mysite.com/cart

Any idea how to fix this?

@rwkyyy
Copy link

rwkyyy commented Nov 3, 2017

Hmm, doesn't work for me :(

#0 /Users/**/Documents/***/wp-includes/class-wp-hook.php(300): add_referral_meta(739) #1 /Users/**/Documents/***/wp-includes/class-wp-hook.php(323): WP_Hook->apply_filters(NULL, Array) #2 /Users/**/Documents/***/wp-includes/plugin.php(453): WP_Hook->do_action(Array) #3 /Users/**/Documents/***/wp-content/plugins/woocommerce/includes/class-wc-checkout.php(339): do_action('woocommerce_che...', 739, Array) #4 /Users/**/Documents/***/wp-content/plugins/woocommerce/includes/class-wc-checkout.php(976): WC_Checkout->create_order(Array) #5 /Users/**/Documents/***/wp-content/plugins/woocommerce/includes/class-wc-ajax.php(409): WC_Checkout->process_checkout() #6 /Users/** in /Users/**/Documents/hi/wp-content/themes/vanzari/functions.php on line 620

@pictibe
Copy link

pictibe commented Apr 21, 2020

Does it work at this time?

@art-n
Copy link

art-n commented Jun 2, 2021

It makes payments using Stripe impossible for me.

@hasanet
Copy link

hasanet commented Jan 17, 2022

Does not work. Checkout page returns "Internal Server Error"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment