arraypress / wp-referrer-utils
A lean WordPress library for HTTP referrer detection and analysis
Requires
- php: >=8.3
Requires (Dev)
- phpcompatibility/phpcompatibility-wp: ^2.1
- phpunit/phpunit: ^12.0
- squizlabs/php_codesniffer: ^3.13.5
- wp-coding-standards/wpcs: ^3.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
This library has moved. It is now part of
sugarcommerce/network(namespaceSugarCommerce\Network, PHP 8.3+). That package's README has a "Moving from arraypress/wp-*" table. This repository is archived and read-only.
Referrer
Work out where a visitor came from, and strip the tracking noise off the URL before you store it.
What it does
The referrer tells you whether somebody arrived from Google, Facebook or a link on someone's blog — but the raw header is a full URL with campaign parameters hanging off it, and answering "was this a search?" means knowing what several hundred search domains look like.
This reads the referrer, says which search engine or social platform it was, and pulls the campaign parameters out separately so what you store is the page rather than the tracking.
The referrer is also the weakest signal there is. Browsers trim it or drop it,
and apps open links in their own browser and send none. So analyse() reads
everything a page knows — the UTM tags and click IDs on the landing page, the
app it opened in, then the referrer — and far fewer visits come out "direct".
The rules are the ones the JavaScript package
@flarecart/referrer uses, so a
visit is filed the same way whichever side saw it.
Features
- File a visit under one of eight channels: search, social, email, AI, paid, campaign, referral or direct
- Tell whether a visit came from a search engine, and which one
- Tell whether it came from social, and which platform
- Tell an AI assistant (ChatGPT, Claude, Perplexity, Gemini) from a search engine, and webmail from both
- Read click IDs (
gclid,ttclid,fbclid,mc_cid), which survive when the referrer does not - Match hosts by whole labels:
old.reddit.comis Reddit, andmicrosoft.comis not Twitter for containingt.co - Ignore a return from Stripe, PayPal or a sign-in page
- Pull UTM and campaign parameters out as their own data
- Strip tracking parameters from a URL without eating its real ones
- Get the domain, or the root domain, without parsing it yourself
- Recognise a referrer from your own site, so internal navigation is not counted
- A brand mark and a colour for each named source, with a plain picture for the rest
- Remember a visitor's first touch in a cookie until they buy or sign up, with every value cut to a tag before it is stored
Installation
composer require arraypress/wp-referrer-utils
Quick start
Record where an order came from, once, at checkout:
$source = get_referrer_source(); // "google", "facebook", or a domain $utm = get_referrer_utm_params(); // campaign, medium, source update_post_meta( $order_id, '_source', $source ); update_post_meta( $order_id, '_utm', $utm );
Or the whole visit, on the landing page:
use ArrayPress\ReferrerUtils\Referrer; $source = Referrer::from_request(); // [ 'channel' => 'paid', 'source' => 'TikTok Ads', 'label' => 'TikTok Ads', // 'click_id' => [ 'param' => 'ttclid', 'network' => 'TikTok Ads' ], ... ] if ( ! $source['internal'] ) { update_post_meta( $order_id, '_channel', $source['channel'] ); update_post_meta( $order_id, '_source', $source['label'] ); }
internal is a referrer from the site itself, or from a checkout or sign-in
page: moving around the site is not a new source, so keep the one the visit
already had.
What beats what, strongest first:
- UTM tags.
utm_mediumsets the channel when it is a known one (cpc,paid_social,newsletter); otherwise a paid click ID makes it paid, a knownutm_sourcelends its channel, and anything else is a campaign. - A click ID.
fbclidandigshcount as social, not paid: Meta adds them to organic links too. - The in-app browser, when you pass one in.
- The referrer: webmail, then AI assistants, then search engines, then social networks, then a referral named by its registered domain.
- Direct.
Cleaning a URL before it is stored or compared:
use ArrayPress\ReferrerUtils\Tracking; $clean = Tracking::strip( $url );
Only vendor-namespaced parameters are stripped — utm_*, fbclid, gclid
and their kind. A bare s or v is left alone, because those are WordPress
search and YouTube video ids, and a global strip list eats both.
Source icons
A picture and a colour for each named source, for a list or a chart of where orders came from:
use ArrayPress\ReferrerUtils\Icons; $source = Referrer::analyse( $input )['source']; // "Reddit", "Brave Search", null Icons::url( (string) $source ); // …/assets/sources/reddit.svg Icons::color( (string) $source ); // "#ff4500", or "" for a source with none Icons::file( 'Fastmail' ); // "email" -- no mark of its own Icons::all(); // [ 'Baidu' => 'baidu', … ]
Keyed by the names the Sources and Campaigns tables give. A source with
no mark gets one of three plain pictures, so every row has one: an arrow for
no source at all, an envelope for an email source, a globe for the rest. The
marks are from Simple Icons
(CC0 1.0) and remain their owners' trademarks; see
assets/sources/README.md.
Icons::url() works out where the library is installed -- vendor/, a
Strauss-prefixed copy, a plugin folder -- and is empty only when that is
somewhere WordPress does not serve.
First-touch attribution
The visit that said where somebody came from is long gone by the time they
buy -- often on a payment provider's page, recorded from a webhook that never
saw the visit. FirstTouch notes the first visit in a cookie, and whatever is
made later (a cart, an order, an account) copies it:
use ArrayPress\ReferrerUtils\FirstTouch; $touch = new FirstTouch( [ 'prefix' => 'myplugin', // cookie and filter: myplugin_first_touch 'lifetime' => 30 * DAY_IN_SECONDS, 'enabled' => fn() => (bool) get_option( 'myplugin_track_source', true ), ] ); $touch->init(); // notes the first visit on template_redirect // Later, when the cart or the sign-up is made: $stored = $touch->stored(); // '{"source":"Google","medium":"search",...}' or '' $source = $touch->decode( $stored ); // [ 'source' => 'Google', 'medium' => 'search', // 'referrer' => 'google.com', 'landing' => '/kits/' ]
First touch, not last: once there is a cookie -- any cookie of that name --
nothing replaces it. A direct visit sets none, and the landing path alone is
never a reason to set one. Switched off (enabled false), it sets no cookie
and reads none that is already there.
Nothing about the person is kept. The referring host, the tags on the
link and the path landed on describe the link, not whoever followed it. A click
ID is kept by its name (gclid), never its value. The cookie is HttpOnly,
SameSite=Lax (so it survives the return from a payment page) and Secure on
HTTPS.
Nothing read back is trusted. The cookie, a copy on a cart, a payment's
metadata: everything goes through clean() -- only the configured fields, each
cut to its length in characters, none empty. The fields somebody typed into a
link (source, medium, campaign, term, content) are also cut to tags
(Referrer::to_tag(): letters, digits and -_.+ , at most 60 characters), so
an AI agent reading orders back through an API finds a campaign name and not an
instruction. Pass 'tags' => [] to keep stored values sanitised as text only.
The fields, chosen by name or by name and length:
| Field | What | Default |
|---|---|---|
source |
Google, Google Ads, the utm_source, or a referring domain |
yes, 100 |
medium |
the utm_medium as tagged, otherwise the channel |
yes, 100 |
campaign |
utm_campaign |
yes, 150 |
referrer |
the referring host, unless it was the site or a payment page | yes, 255 |
landing |
the path landed on, no query | yes, 255 |
term, content |
utm_term, utm_content |
no |
channel |
search, social, email, ai, paid, campaign, referral |
no |
click_id |
the click ID's parameter, e.g. gclid |
no |
$touch = new FirstTouch( [ 'cookie' => 'myplugin_src', 'fields' => [ 'source' => 100, 'medium' => 100, 'campaign', 'click_id' ], 'in_app' => [ UserAgent::class, 'in_app_browser' ], // TikTok's browser sends no referrer 'ignore' => [ 'pay.example.org' ], // more hosts that are never a source 'filter' => 'myplugin_order_source', // instead of {prefix}_first_touch ] ); $touch->fields(); // [ 'source' => 100, ... ] -- your columns
The filter ({prefix}_first_touch, or the name given) gets the payload, what
Referrer::analyse() decided, the referrer and the landing address. Return an
empty array to record nothing; what comes back is cleaned:
add_filter( 'myplugin_first_touch', function ( array $payload, array $found, string $referrer, string $landing ) { return 'direct' === $found['channel'] && str_contains( $landing, 'ref=podcast' ) ? [ 'source' => 'podcast' ] : $payload; }, 10, 4 );
A headless front end that sends its own visit can use from_visit() directly:
$payload = $touch->from_visit( $referrer, $landing_url, home_url() ); $json = $touch->encode( $payload );
Copying it onto a payment that keeps string pairs (a Stripe Checkout Session's metadata), and reading it back when the cart is gone:
$metadata = $touch->to_metadata( $touch->decode( $cart->source ), 'myplugin_' ); // [ 'myplugin_source' => 'Google', 'myplugin_medium' => 'search', ... ] -- no empty keys $columns = $touch->from_metadata( $session->metadata, 'myplugin_' ) + $touch->blank();
current() is the cookie read back, stored() the same as JSON, and
forget() clears it.
A page served from a full-page cache never reaches PHP, so a visit that only ever sees cached pages is not noted: a conversion read as direct rather than one read wrongly.
Requirements
- PHP 8.3 or later
- WordPress 7.1 or later
License
GPL-2.0-or-later