add referrer to woo

The code in the original article is broken, and would’ve been broken when it was written. So being outdated is not the problem (2 years is nothing in WordPress time).

The issue is this line:

add_action('woocommerce_checkout_update_order_meta', 'add_referral_meta');

The callback function they’ve created, add_referral_meta(), accepts two arguments, $order_id and $posted:

function add_referral_meta( $order_id, $posted ) {

But if a callback function accepts more than one argument, the add_action() call needs to specify how many. So that first line of code needs to look like this:

add_action( 'woocommerce_checkout_update_order_meta', 'add_referral_meta', 10, 2 );

You can read more about how actions work in WordPress in the developer documentation.

That being said, this isn’t a future-proof solution, since it’s not using the proper WooCommerce methods for saving order meta. I suggest using this code instead:

function wpse_330106_set_origin_cookie() {
    $cookie_value = $_SERVER['HTTP_REFERER'];

    if ( ! is_admin() && ! isset( $_COOKIE['origin'] ) ) {
        setcookie( 'origin', $cookie_value, time() + 3600*24*30, COOKIEPATH, COOKIE_DOMAIN, false );
    }
}
add_action( 'init', 'wpse_330106_set_origin_cookie');

function wpse_330106_add_order_referrer( $order ) {
    $order->add_meta_data( 'referrer', $_COOKIE['origin'] );
}
add_action('woocommerce_checkout_create_order', 'wpse_330106_add_order_referrer', 10, 1 );

This solution uses the more modern $order->add_meta_data() method, which is the current proper way to add meta data to WooCommerce orders these days. This is because it will continue to work regardless of where WooCommerce stores its order data. This will be useful when WooCommerce inevitable starts storing orders in a custom table, rather than as posts.