<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Rasel Hakkani on WordPress]]></title><description><![CDATA[Rasel Hakkani on WordPress]]></description><link>https://raselhk.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6afa00a4b5785800dd33a02a/4b6ecd8e-54c7-4a47-8045-dd9646a13616.jpg</url><title>Rasel Hakkani on WordPress</title><link>https://raselhk.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Wed, 18 Nov 2026 14:51:06 GMT</lastBuildDate><atom:link href="https://raselhk.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Post-purchase survey for WooCommerce: what to ask and how to read it]]></title><description><![CDATA[What to ask in a WooCommerce post-purchase survey, why zero-party data catches what analytics misses, and how to get revenue by channel.]]></description><link>https://raselhk.hashnode.dev/post-purchase-survey-for-woocommerce-what-to-ask-and-how-to-read-it</link><guid isPermaLink="true">https://raselhk.hashnode.dev/post-purchase-survey-for-woocommerce-what-to-ask-and-how-to-read-it</guid><category><![CDATA[woocommerce]]></category><category><![CDATA[WordPress]]></category><category><![CDATA[ecommerce]]></category><category><![CDATA[marketing]]></category><category><![CDATA[analytics]]></category><dc:creator><![CDATA[Rasel Hakkani]]></dc:creator><pubDate>Sun, 15 Nov 2026 19:53:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6afa00a4b5785800dd33a02a/e603d28c-68ce-408e-9881-ce8d12de485a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Every WooCommerce store collects data about its customers. Most of it is observed: pages viewed, the last click before an order, the device. A post-purchase survey collects a different kind, the kind a customer hands you on purpose. That is zero-party data, and one question in particular, "How did you hear about us?", can show you channels your tracking never sees.</p>
<p>This guide covers what to ask after checkout, which questions buyers actually answer, and how to turn their answers into revenue by channel. About me: I am Rasel Hakkani, I build WordPress plugins, and SourceSay, a <a href="https://swiftwebdev.com/sourcesay/">free post-purchase survey plugin for WooCommerce</a>, is one of mine. I mention it where it helps, but the method works with any survey tool.</p>
<h2>What is zero-party data?</h2>
<p>Zero-party data is information a customer chooses to give you directly: an answer, a preference, a reason. The research firm Forrester popularized the term to set it apart from first-party data, which you observe (clicks, orders, browsing), and third-party data, which someone else collected.</p>
<p>The difference matters for attribution. Click tracking can only record what happened in a browser it could see. Zero-party data records what the customer says happened, including the parts that took place nowhere near your website.</p>
<p>For a store, a post-purchase survey is the simplest zero-party source there is. It is one question, asked to someone who just paid, with no signup and no extra step before checkout.</p>
<h2>Why self-reported attribution fills the gaps analytics leave</h2>
<p>Analytics tools and WooCommerce's own Order Attribution (on by default since WooCommerce 8.5) both work from clicks. When a visit arrives with no referrer, the order is labeled Direct. When no tracking data reaches the order, it shows as Unknown.</p>
<p>Plenty of real discovery produces no click to record:</p>
<ul>
<li><strong>Dark social.</strong> A friend sends your product link in WhatsApp, Slack or a DM. Many apps pass no referrer, so the visit looks typed in.</li>
<li><strong>Podcasts and audio.</strong> The listener hears your name or a code, then types the address later.</li>
<li><strong>Word of mouth.</strong> A recommendation over dinner leaves nothing to track.</li>
<li><strong>Creator videos.</strong> Watched on a phone, bought days later on a laptop.</li>
<li><strong>AI assistants.</strong> ChatGPT, Perplexity and others now recommend products in their answers. A click inside the chat may carry a referrer, but a buyer who copies the link or types your name arrives as Direct. I wrote a longer piece on <a href="https://swiftwebdev.com/blog/chatgpt-ai-traffic-wordpress/">how ChatGPT traffic shows up in WordPress</a> and how to spot it.</li>
</ul>
<p>Self-reported attribution simply means asking the buyer and recording the answer. It does not replace click tracking. It covers the part click tracking cannot see, and it is most useful when you read the two together.</p>
<h2>What question should a post-purchase survey ask?</h2>
<p>Start with the classic: "How did you hear about us?" It is short, everyone understands it, and the answers map onto marketing channels without any cleanup.</p>
<p>Two variations are worth a look:</p>
<ul>
<li><strong>"How did you first hear about us?"</strong> Use it when buyers usually meet you several times before they buy. It points them at the first contact, the one analytics struggles with most.</li>
<li><strong>"What led you to our store today?"</strong> This asks about the final push instead. It overlaps more with what your tracking already records, so it tends to add less.</li>
</ul>
<p>Settle on one wording and leave it alone. If you switch mid-quarter, the before and after numbers stop being comparable.</p>
<h3>Which post-purchase questions earn answers?</h3>
<p>The questions buyers answer have a few things in common:</p>
<ul>
<li><strong>One tap.</strong> Multiple choice beats a text box. Typing on a phone right after paying is a lot to ask.</li>
<li><strong>Your channels, in your words.</strong> List the places you actually market. "Radio or TV" on a store that never bought airtime just takes up room.</li>
<li><strong>A way out.</strong> "Other" with a short text box catches the channels you forgot. A "Prefer not to say" button lets people skip without picking something at random.</li>
<li><strong>Detail only where it pays.</strong> A follow-up like "Which podcast?" or "Who should we thank?" on one or two answers tells you which show or which customer sends buyers. A follow-up on every answer turns one question into a second survey.</li>
<li><strong>Optional.</strong> A required question gets more answers, and more rushed ones.</li>
</ul>
<h2>How many questions should a post-purchase survey have?</h2>
<p>One, to start. Each extra question gives the buyer another reason to close the tab, and the first question is the one you need most. After a few weeks of answers you will know which channel deserves a follow-up, and you can grow from there.</p>
<p>The free SourceSay plugin follows that pattern: one question on the order confirmation page, with optional follow-ups on the answers you choose.</p>
<h2>Are customers misremembering how they found you?</h2>
<p>Sometimes, yes. Self-reported data has known biases, and you can design around most of them:</p>
<ul>
<li><strong>Recency.</strong> People name the last thing they remember. The "first hear" wording pushes back on this a little.</li>
<li><strong>Position.</strong> Options at the top of a list get picked more often just for being first. Shuffle the order for each buyer. SourceSay does this by default and keeps "Other" at the bottom.</li>
<li><strong>Memorable beats accurate.</strong> A friend's tip sticks better than a banner ad seen three times. That is not always wrong, though. The friend may be the real reason they bought.</li>
<li><strong>Who answers.</strong> You only hear from buyers who chose to answer. Check that the response rate is steady before you compare channels across months.</li>
</ul>
<p>None of this means the answers are useless. It means they are one view of what happened, and they get much stronger next to a second view.</p>
<h2>How do I combine "how did you hear about us?" answers with analytics data?</h2>
<p>Start order by order. Each order can carry two labels: the source WooCommerce Order Attribution tracked, and what the customer said. Put them side by side.</p>
<img src="https://ps.w.org/sourcesay/assets/screenshot-6.png" alt="WooCommerce Orders list with a Heard about us column showing each customer's answer next to the Origin column WooCommerce tracked" style="display:block;margin:0 auto" />

<p><em>The orders list: what each customer said, next to the origin WooCommerce tracked.</em></p>
<p>Patterns show up fast. An order tracked as Direct with the answer "Podcast" is a podcast sale your analytics missed. An order tracked as Organic search with the answer "Friend or family" is a recommendation that ended in a Google search for your name. Neither label is wrong. Together they tell the whole story.</p>
<p>Two habits keep this honest:</p>
<ol>
<li><strong>Never overwrite one label with the other.</strong> The survey does not fix a Direct or Unknown label, and it should not try. Keep both and compare.</li>
<li><strong>Read groups, not single orders.</strong> One odd answer means nothing. A stack of Direct orders where most buyers named the same podcast is a finding.</li>
</ol>
<p>SourceSay shows both labels in the orders list, on each order screen and in the CSV export, which has columns for the WooCommerce source type and source, so you can pivot them yourself. If you would rather have that grouping done for you, <a href="https://swiftwebdev.com/sourcesay-pro/">SourceSay Pro's blind spot report</a> groups answered orders by tracked source and splits each group by what those buyers said. It is an optional add-on, and the free plugin has no response limit.</p>
<h2>How to turn answers into revenue by channel</h2>
<p>A count of answers tells you where people say they came from. Revenue attribution tells you what those people were worth. The bridge between the two is storing each answer with its order total.</p>
<p>Once every answer carries a total, five numbers do most of the work:</p>
<ol>
<li><strong>Revenue per channel.</strong> Add up answered orders by answer, using totals after refunds. Otherwise a channel that brings refund-happy buyers looks better than it is.</li>
<li><strong>Average order value per channel.</strong> Revenue divided by answered orders. Some channels send fewer people who spend more.</li>
<li><strong>Share of answers vs share of revenue.</strong> If Podcast holds a small slice of answers but a bigger slice of revenue, podcast buyers spend more per order. That calls for a different decision than "Podcast is small".</li>
<li><strong>New vs returning buyers.</strong> A channel that mostly brings back past customers is doing retention work, not discovery.</li>
<li><strong>The previous period.</strong> Compare against the same length of time before, so one quiet week does not look like a failing channel.</li>
</ol>
<img src="https://ps.w.org/sourcesay/assets/screenshot-2.png" alt="SourceSay channel table with each channel's answers, revenue, average order and bars comparing share of answers with share of revenue" style="display:block;margin:0 auto" />

<p><em>Share of answers next to share of revenue for each channel, plus the daily trend (demo store data).</em></p>
<p>SourceSay's Reports tab calculates these from the stored totals, and refunds and status changes update them, so the numbers stay true when orders change. The docs explain <a href="https://swiftwebdev.com/sourcesay/docs/">how to read the revenue by channel report</a> column by column.</p>
<p>Then read the follow-up answers. "Podcast" as a channel is useful. Knowing which show sent the buyers is what you bring to the next sponsorship conversation. And when the same name keeps turning up under "Other", that channel has earned its own option in the list.</p>
<h2>Getting started</h2>
<p>To try this on your own store, <a href="https://wordpress.org/plugins/sourcesay/">install SourceSay from the WordPress.org plugin directory</a>. It needs WooCommerce, takes a few minutes to set up with a test order, and the answers never leave your own site.</p>
<p>Prefer to watch before you install? Here is a <a href="https://www.youtube.com/watch?v=9ZqegBlDer0">short video on adding the survey to WooCommerce</a>.</p>
<p>Whatever tool you use, the method is the same: ask one optional question after payment, store the answer with the order total, and read it next to your analytics rather than in place of it.</p>
]]></content:encoded></item><item><title><![CDATA[How cookieless analytics counts real visitors without storing IPs]]></title><description><![CDATA[How cookieless analytics works: a daily salted hash, no stored IPs, a human check that keeps headless bots out, and the real IP behind Cloudflare.]]></description><link>https://raselhk.hashnode.dev/how-cookieless-analytics-counts-real-visitors-without-storing-ips</link><guid isPermaLink="true">https://raselhk.hashnode.dev/how-cookieless-analytics-counts-real-visitors-without-storing-ips</guid><category><![CDATA[WordPress]]></category><category><![CDATA[analytics]]></category><category><![CDATA[privacy]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[PHP]]></category><dc:creator><![CDATA[Rasel Hakkani]]></dc:creator><pubDate>Sun, 15 Nov 2026 19:50:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6afa00a4b5785800dd33a02a/1aac2dfc-9eac-4e2f-8b85-0c2e9b1846df.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Counting page views is easy. Counting people is the hard part. To know that two page views came from the same person, a classic analytics tool drops a cookie with a random ID or keeps the IP address in a log. Those are exactly the two things privacy-minded site owners want to avoid. Cookieless analytics is the family of techniques that answers "how many people?" without either.</p>
<p>I built <a href="https://swiftwebdev.com/wordpress-visitor-statistics/">a cookieless WordPress visitor statistics plugin</a>, and this post explains the method it uses, with simplified code you can adapt to any stack. I also cover the part most write-ups skip: why a counter that fires on page load overcounts badly now that so many bots run JavaScript, and how to tell a person from a headless browser without fingerprinting anyone.</p>
<h2>What does cookieless analytics mean?</h2>
<p>Cookieless analytics counts visits without storing anything in the visitor's browser: no cookies, no localStorage, no IndexedDB. Whatever identifies a visit is computed on the server, used for a moment and thrown away. You give up a few things in return (listed near the end), but you keep the numbers most site owners actually look at: visitors, page views, sessions, top pages and referrers.</p>
<p>The hard word is "visitors". With no ID in the browser, the server has to recognize repeat page views from the request alone. If your question is the practical one, how to get stats into WordPress without a Google account, I covered that in <a href="https://swiftwebdev.com/blog/wordpress-analytics-without-google-analytics/">WordPress analytics without Google Analytics</a>. This post is about the mechanics.</p>
<h2>A daily salted hash instead of a stored ID</h2>
<p>Every request carries an IP address and a user agent string. Together they make a decent short-term identifier: the same phone on the same Wi-Fi sends the same pair all afternoon. The trick is to hash that pair with a secret salt and keep only the hash.</p>
<pre><code class="language-php">&lt;?php
// Simplified from the plugin. Runs on every counter request.
function visitor_hash( string $ip, string $ua ): string {
	$today = wp_date( 'Y-m-d' ); // site-local date
	$salt  = get_option( 'demo_daily_salt' );

	if ( ! is_array( $salt ) || $salt['date'] !== $today ) {
		// New day: a fresh random salt overwrites yesterday's.
		$salt = array(
			'date' =&gt; $today,
			'salt' =&gt; wp_generate_password( 32, true, true ),
		);
		update_option( 'demo_daily_salt', $salt, false );
	}

	return hash( 'sha256', $salt['salt'] . $ip . $ua );
}
</code></pre>
<p>Three details carry the privacy weight:</p>
<ul>
<li><strong>The salt is random and secret.</strong> A plain SHA-256 of an IPv4 address is not anonymous. There are only about 4.3 billion addresses, and an ordinary computer can hash all of them in short order. A random salt that an attacker does not have makes that lookup useless.</li>
<li><strong>The salt rotates every day.</strong> Yesterday's salt is overwritten, so yesterday's hashes can no longer be recomputed or matched against today's. The same person gets a new, unrelated hash each day.</li>
<li><strong>The raw values are never written.</strong> The IP and user agent exist in memory for the length of one request.</li>
</ul>
<p>One honest edge case: during the current day, the salt sits in the database. Someone with database access who already knows a specific IP and user agent could recompute today's hash for that pair. After the day rolls over, they cannot.</p>
<h2>What actually gets stored</h2>
<p>One row per page load, and nothing else:</p>
<pre><code class="language-sql">CREATE TABLE wp_swiftdash_hits (
  id          BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  visitor     CHAR(64) NOT NULL,            -- sha256(daily salt + IP + user agent)
  token       CHAR(16) NOT NULL,            -- random id of one page load
  human       TINYINT(1) UNSIGNED NOT NULL, -- 0 until a person is confirmed
  new_session TINYINT(1) UNSIGNED NOT NULL,
  created     DATETIME NOT NULL,
  PRIMARY KEY (id)
);
</code></pre>
<p>No IP, no user agent, not even the URL. The page path goes straight into a daily per-page counter and is never tied to the visit row. An hourly job rolls the raw rows up into daily totals, and raw rows older than 48 hours are deleted:</p>
<pre><code class="language-sql">SELECT COUNT(DISTINCT IF(human = 1, visitor, NULL)) AS visitors,
       SUM(human = 1)                               AS page_views,
       SUM(IF(human = 1, new_session, 0))           AS sessions,
       SUM(human = 0)                               AS automated
FROM wp_swiftdash_hits
WHERE created &gt;= '2026-11-15 00:00:00'
  AND created &lt;  '2026-11-16 00:00:00';
</code></pre>
<p>Daily totals are kept for 180 days, and daily counts per page, referrer and device type for 90 days. Sessions fall out of the same table: a confirmed page view starts a new session when the same hash has no confirmed page view in the 30 minutes before it.</p>
<img src="https://ps.w.org/swiftwebdev-dashboard-analytics/assets/screenshot-1.png" alt="SwiftWebDev Dashboard showing Visitors, Page views and Sessions cards with trend lines above a visitors over time bar chart and a busiest days list" style="display:block;margin:0 auto" />

<p><em>The daily totals are all the dashboard needs. Demo site with sample data.</em></p>
<h2>Why page-load beacons overcount</h2>
<p>Most lightweight counters send one request when the page loads, often called a beacon. That used to be a reasonable stand-in for a person, because most bots did not run JavaScript. Many now do. Headless Chrome is cheap, scrapers use it to read client-rendered pages, and SEO tools render pages the way a browser does. Every one of them executes your counter script and fires the beacon.</p>
<p>You can drop the polite ones by user agent: anything that says "bot", "crawl", "spider" or "headless" gets ignored. The rest present themselves as ordinary Chrome.</p>
<p>I saw this on my own site this month. One client with a single, identical desktop Chrome user agent loaded pages from a dozen countries, came in through odd URLs, stayed between zero and four seconds and never moved a mouse, scrolled or clicked in the session recordings. My counter, which still fired on page load at the time, recorded every one of those loads as a visit.</p>
<h2>The human check</h2>
<p>The fix is to split counting into two steps. The page load is recorded as pending. It turns into a visit only after real input or real reading time.</p>
<pre><code class="language-js">// Simplified version of the counter script.
(function () {
  if (navigator.webdriver) return; // WebDriver-controlled browsers set this flag

  var endpoint = '/wp-json/demo/v1/hit';
  var id = Array.from(crypto.getRandomValues(new Uint8Array(8)), function (b) {
    return ('0' + b.toString(16)).slice(-2);
  }).join('');
  var signals = ['pointermove', 'mousemove', 'wheel', 'keydown', 'click', 'touchstart'];
  var human = false;
  var seconds = 0;
  var timer;

  function send(data) {
    navigator.sendBeacon(endpoint, JSON.stringify(data));
  }

  function markHuman(event) {
    if (human || (event &amp;&amp; !event.isTrusted)) return; // ignore events made by scripts
    human = true;
    clearInterval(timer);
    signals.forEach(function (type) {
      removeEventListener(type, markHuman, true);
    });
    send({ i: id, p: location.pathname, h: 1 }); // step 2: a person is here
  }

  send({ i: id, p: location.pathname }); // step 1: a page loaded

  signals.forEach(function (type) {
    addEventListener(type, markHuman, { capture: true, passive: true });
  });

  // Reading without touching anything also counts: 10 seconds visible in total.
  timer = setInterval(function () {
    if (document.visibilityState === 'visible' &amp;&amp; ++seconds &gt;= 10) markHuman();
  }, 1000);
})();
</code></pre>
<p>Why each choice:</p>
<ul>
<li><code>isTrusted</code><strong>.</strong> Events created with <code>dispatchEvent()</code> carry <code>isTrusted === false</code>. A script on the page can fake a click, but not a trusted one. Tools that drive a real browser through its debugging protocol can still produce trusted input, so treat this as a filter, not proof.</li>
<li><code>wheel</code><strong>, not</strong> <code>scroll</code><strong>.</strong> Pages scroll themselves (anchor links, scroll restoration) and crawlers scroll by script to trigger lazy loading. A <code>scroll</code> event fires for all of that. A <code>wheel</code> event needs a wheel or a trackpad. Touch scrolling is covered by <code>touchstart</code>, keyboard scrolling by <code>keydown</code>.</li>
<li><strong>Ten seconds of visibility.</strong> Some people read without touching anything. Counting only while <code>document.visibilityState</code> is <code>'visible'</code> keeps background tabs and prerendered pages out. The server also ignores requests sent with a prefetch purpose header.</li>
<li><strong>Two requests, one token.</strong> The server matches the confirmation to the pending row by token and visitor hash, flips <code>human</code> to 1, and only then adds the page to the per-page totals. Rows that never confirm become "automated visits", which is a useful number on its own.</li>
</ul>
<h2>Crawlers that never run your script</h2>
<p>Many crawlers, including most AI crawlers, fetch the HTML without running any JavaScript, so a script-based counter never sees them. Those are counted on the server instead. On each request, WordPress checks the user agent against known names such as GPTBot, ClaudeBot, PerplexityBot, Googlebot, Bingbot and AhrefsBot, and adds one to a daily total per crawler. Again, no IP, user agent or URL is stored.</p>
<p>Two caveats apply. User agents can be faked, so a name is a claim, not proof of identity. And when a page cache answers before WordPress loads, the request is invisible to the plugin, so crawler counts are a minimum.</p>
<img src="https://ps.w.org/swiftwebdev-dashboard-analytics/assets/screenshot-4.png" alt="AI crawlers card listing bot visits by company with training, AI search and asked-by-a-user splits, next to a Bots and automated visits card with automated browser visits, AI crawlers and search and SEO crawlers marked as not counted as visitors" style="display:block;margin:0 auto" />

<p><em>Bots and automated visits get their own card and never count as visitors. Demo site with sample data.</em></p>
<h2>Finding the real visitor IP behind Cloudflare</h2>
<p>The hash is only as good as its input. Behind Cloudflare or a load balancer, <code>REMOTE_ADDR</code> is the proxy, not the visitor. Hash that and the input changes with whichever edge server forwarded the request: one reader can split into several "visitors", and different readers can merge into one. On my own Cloudflare site, visitors came out almost equal to page views, which is what gave it away.</p>
<p>The fix is to read the forwarded header, but only from a source you trust:</p>
<pre><code class="language-php">&lt;?php
// Simplified. CLOUDFLARE_RANGES is the list published at cloudflare.com/ips,
// and ip_in_ranges() is a plain CIDR check.
function client_ip(): string {
	$ip = $_SERVER['REMOTE_ADDR'] ?? '';
	$cf = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? '';

	// Trust CF-Connecting-IP only when the request really came from Cloudflare.
	if ( $cf &amp;&amp; filter_var( $cf, FILTER_VALIDATE_IP ) &amp;&amp; ip_in_ranges( $ip, CLOUDFLARE_RANGES ) ) {
		return $cf;
	}

	// Behind a private proxy, take the first public address in X-Forwarded-For,
	// reading from the right.
	$public = FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE;
	if ( filter_var( $ip, FILTER_VALIDATE_IP ) &amp;&amp; ! filter_var( $ip, FILTER_VALIDATE_IP, $public )
		&amp;&amp; ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
		foreach ( array_reverse( explode( ',', $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) as $hop ) {
			if ( filter_var( trim( $hop ), FILTER_VALIDATE_IP, $public ) ) {
				return trim( $hop );
			}
		}
	}

	return $ip;
}
</code></pre>
<p>The ordering is the point. Anyone can send a <code>CF-Connecting-IP</code> header straight to your origin server, so it only counts when <code>REMOTE_ADDR</code> sits inside Cloudflare's published ranges. With <code>X-Forwarded-For</code>, each proxy appends to the right and the left side is whatever the client claimed, so you read from the right and stop at the first public address. The plugin hardcodes Cloudflare's ranges, which rarely change, and offers a <code>swiftdash_client_ip</code> filter for other setups.</p>
<h2>What you give up</h2>
<ul>
<li><strong>No identity across days.</strong> Period totals simply add up the daily uniques. Over 30 days, a reader who returns on three separate days is three visitors, and there is no new versus returning split.</li>
<li><strong>Shared networks can merge people.</strong> Two coworkers behind the same office IP with the same browser and OS version produce the same hash that day.</li>
<li><strong>Quick bounces are not counted.</strong> A visit shorter than 10 seconds with no input at all is recorded as automated. I would rather miss a few people than count every headless browser.</li>
<li><strong>No JavaScript, no visit.</strong> Visitors with scripts turned off never pass the human check.</li>
<li><strong>Referrer-based sources undercount.</strong> AI assistants are the clearest case: several of their apps open links with no referring address, so those clicks look like direct traffic.</li>
</ul>
<h2>Does cookieless analytics need a cookie banner?</h2>
<p>It is the first question everyone asks, and I cannot answer it for your site. What I can say about this method: it sets no cookies, uses no browser storage and stores no IP addresses. Whether a banner is needed depends on everything else your site loads (embeds, ads, other plugins) and on your visitors' countries. Read this as an engineering description, not legal advice.</p>
<h2>Try it or read the code</h2>
<p>If you run WordPress, the plugin is free on <a href="https://wordpress.org/plugins/swiftwebdev-dashboard-analytics/">its WordPress.org page</a> as SwiftWebDev Dashboard, and the visitor counter lives in two readable files: <code>assets/js/tracker.js</code> and <code>includes/tracker.php</code>.</p>
<p><a href="https://swiftwebdev.com/wordpress-visitor-statistics/docs/">The documentation</a> walks through each dashboard card and setting.</p>
<p>If you are weighing it against a Google Analytics based plugin, here is <a href="https://swiftwebdev.com/monsterinsights-alternative/">how it compares with MonsterInsights</a>.</p>
<p>And if you are building a counter in another stack, take the two-step human check with you. It removed more noise from my numbers than anything else I tried.</p>
]]></content:encoded></item><item><title><![CDATA[Custom REST API Integration for WordPress: Endpoints, Auth and Caching Done Right]]></title><description><![CDATA[This guide was first published on Swift Web Dev, where it stays up to date. Sooner or later every serious WordPress site has to talk to something that is…]]></description><link>https://raselhk.hashnode.dev/custom-rest-api-integration-for-wordpress-endpoints-auth-and-caching-done-right</link><guid isPermaLink="true">https://raselhk.hashnode.dev/custom-rest-api-integration-for-wordpress-endpoints-auth-and-caching-done-right</guid><category><![CDATA[WordPress]]></category><category><![CDATA[REST API]]></category><category><![CDATA[PHP]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Rasel Hakkani]]></dc:creator><pubDate>Sun, 15 Nov 2026 19:28:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6afa00a4b5785800dd33a02a/a913a23a-8236-40bb-9e68-37bd6f5f65eb.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>This guide was first published on</em> <a href="https://swiftwebdev.com/blog/custom-rest-api-integration-wordpress-guide/"><em>Swift Web Dev</em></a><em>, where it stays up to date.</em></p>
<p>Sooner or later every serious WordPress site has to talk to something that is not WordPress: a mobile app, an ERP, a React front end, a partner’s ordering system, a CRM that needs every new lead within seconds. The built-in endpoints under <code>/wp-json/wp/v2/</code> get you part of the way, then you hit the wall. You need computed data, write access with proper permissions, webhooks that arrive when you are asleep, and responses fast enough that the other system does not time out. That is custom REST API integration for WordPress, and it is most of what we build on our <a href="https://swiftwebdev.com/services/custom-rest-api-integration/">custom REST API integration service</a>.</p>
<p>This post is for a CTO, product owner or lead developer who has a concrete integration to ship and wants to know what “done right” looks like before scoping it. We cover the three integration directions, how to register endpoints properly, which authentication method fits which client, validation and errors, caching that does not serve stale data, and how we test it all. Code samples are from patterns we ship, simplified for reading.</p>
<h2>What custom REST API integration for WordPress actually covers</h2>
<p>Integrations fall into three directions, and most real projects need at least two of them:</p>
<table>
<thead>
<tr>
<th>Direction</th>
<th>Example</th>
<th>Main risk</th>
</tr>
</thead>
<tbody><tr>
<td>Expose WordPress data</td>
<td>A React app or mobile app reads products, posts and ACF fields</td>
<td>Slow responses, over-exposure of private data</td>
</tr>
<tr>
<td>Accept data into WordPress</td>
<td>A CRM or payment provider posts a webhook that creates or updates records</td>
<td>Unauthenticated writes, duplicate processing</td>
</tr>
<tr>
<td>WordPress calls an external API</td>
<td>New orders sync to an ERP; leads push to HubSpot</td>
<td>Blocking page loads, silent failures, no retry</td>
</tr>
</tbody></table>
<p>The first direction is what people usually mean by “the REST API”, and it is the backbone of every headless build, as we show in our <a href="https://swiftwebdev.com/blog/headless-wordpress-react-step-by-step/">step-by-step headless WordPress with React guide</a>. The second and third are where most production incidents happen, because they involve writes, secrets and network calls that can fail.</p>
<h2>Registering endpoints the right way</h2>
<p>Custom endpoints belong in a plugin, not the theme, under your own namespace with a version number. Every route needs a <code>permission_callback</code> (WordPress has warned about missing ones since 5.5) and every argument needs validation and sanitisation. Here is the shape we use for a read endpoint that returns a computed price list:</p>
<pre><code class="language-plaintext">&lt;?php
add_action( 'rest_api_init', function () {
    register_rest_route( 'swift/v1', '/pricing/(?P&lt;sku&gt;[a-z0-9-]+)', [
        'methods'             =&gt; WP_REST_Server::READABLE,
        'callback'            =&gt; 'swift_get_pricing',
        'permission_callback' =&gt; '__return_true', // public read
        'args'                =&gt; [
            'sku' =&gt; [
                'required'          =&gt; true,
                'validate_callback' =&gt; fn( $v ) =&gt; (bool) preg_match( '/^[a-z0-9-]{3,40}$/', $v ),
                'sanitize_callback' =&gt; 'sanitize_key',
            ],
            'currency' =&gt; [
                'default' =&gt; 'USD',
                'enum'    =&gt; [ 'USD', 'EUR', 'GBP' ],
            ],
        ],
    ] );
} );

function swift_get_pricing( WP_REST_Request $request ) {
    $product = wc_get_product_id_by_sku( $request['sku'] );
    if ( ! $product ) {
        return new WP_Error( 'swift_not_found', 'Unknown SKU', [ 'status' =&gt; 404 ] );
    }
    $data = swift_build_price_table( $product, $request['currency'] );
    return rest_ensure_response( $data );
}
</code></pre>
<p>Two details matter here. Returning a <code>WP_Error</code> with a status gives the client a proper HTTP code and a JSON body it can parse. And <code>rest_ensure_response()</code> lets you set headers later, which we will use for caching. Once an API grows past four or five routes, move to a class that extends <code>WP_REST_Controller</code> so you get schema, <code>prepare_item_for_response()</code> and consistent collection parameters for free.</p>
<h2>Authentication: pick the method that fits the client</h2>
<p>The right auth method depends on who is calling. Using the wrong one is the most common security finding in the API audits we run.</p>
<ul>
<li><strong>Cookie plus nonce.</strong> For JavaScript running on the WordPress site itself. Send <code>X-WP-Nonce</code> from <code>wp_create_nonce( 'wp_rest' )</code>. Useless for anything external.</li>
<li><strong>Application Passwords.</strong> Built into core since 5.6. Basic auth over HTTPS with a per-application password tied to a real user. Our default for server-to-server calls and headless previews. Create a dedicated user with a minimal custom role, never an administrator.</li>
<li><strong>JWT.</strong> Use the JWT Authentication for WP REST API plugin when a mobile app logs users in and holds a token. Rotate the secret key and set short expiry.</li>
<li><strong>OAuth 2.</strong> Only when third parties need delegated access on behalf of your users. Heavier to run; the WP OAuth Server plugin handles the flow.</li>
<li><strong>HMAC-signed webhooks.</strong> For inbound calls from Stripe, HubSpot, Shopify or your own systems. No user account involved; the caller signs the body with a shared secret.</li>
</ul>
<p>For inbound webhooks, the permission callback verifies the signature and the callback rejects duplicates using the provider’s event ID:</p>
<pre><code class="language-plaintext">&lt;?php
function swift_verify_webhook( WP_REST_Request $request ) {
    $secret    = getenv( 'CRM_WEBHOOK_SECRET' ) ?: '';
    $signature = $request-&gt;get_header( 'x-signature' );
    $expected  = hash_hmac( 'sha256', $request-&gt;get_body(), $secret );
    if ( ! $signature || ! hash_equals( $expected, $signature ) ) {
        return new WP_Error( 'swift_bad_signature', 'Invalid signature', [ 'status' =&gt; 401 ] );
    }
    return true;
}

function swift_handle_lead( WP_REST_Request $request ) {
    $event_id = sanitize_text_field( $request['event_id'] );
    if ( get_transient( 'swift_evt_' . $event_id ) ) {
        return rest_ensure_response( [ 'status' =&gt; 'duplicate' ] ); // idempotent
    }
    set_transient( 'swift_evt_' . $event_id, 1, DAY_IN_SECONDS );
    as_enqueue_async_action( 'swift_process_lead', [ $request-&gt;get_json_params() ] );
    return new WP_REST_Response( [ 'status' =&gt; 'queued' ], 202 );
}
</code></pre>
<p>Note the <code>202 Accepted</code> and the hand-off to Action Scheduler. The webhook returns in milliseconds; the actual work (creating a post, calling another API, sending mail) runs in the background where a failure can be retried and logged instead of making the sender give up. WooCommerce ships Action Scheduler; on non-commerce sites install it as a library.</p>
<h2>Validation, errors and versioning</h2>
<p>Define a schema for every route. WordPress uses it to validate request bodies, generate the <code>OPTIONS</code> response that API clients read, and filter output through <code>_fields</code>. Keep error codes stable and namespaced (<code>swift_not_found</code>, <code>swift_rate_limited</code>) because client code will branch on them. When you need to change a response shape, add <code>swift/v2</code> and keep v1 serving for a documented period rather than editing v1 in place. Also filter <code>rest_authentication_errors</code> to block anonymous access to <code>/wp/v2/users</code>, which otherwise lists every author login on the site.</p>
<h2>Caching that does not serve stale data</h2>
<p>An endpoint that runs six <code>WP_Query</code> calls and joins <code>wp_postmeta</code> three times will take 400 ms or more on a busy site. The fix is layered:</p>
<ol>
<li><strong>Object cache.</strong> Install Redis Object Cache and enable it with <code>wp redis enable</code>. Every <code>get_transient()</code> and <code>wp_cache_get()</code> now hits memory instead of <code>wp_options</code>.</li>
<li><strong>Endpoint-level cache with invalidation.</strong> Cache the built response under a key and clear it when the source data changes.</li>
<li><strong>HTTP cache headers.</strong> Set <code>Cache-Control</code> on public GET responses so CloudFront, Cloudflare or the host’s edge cache handles repeat traffic without touching PHP.</li>
</ol>
<pre><code class="language-plaintext">&lt;?php
function swift_get_pricing( WP_REST_Request $request ) {
    $key  = 'swift_price_' . md5( $request['sku'] . $request['currency'] );
    $data = wp_cache_get( $key, 'swift_api' );
    if ( false === $data ) {
        $data = swift_build_price_table( wc_get_product_id_by_sku( $request['sku'] ), $request['currency'] );
        wp_cache_set( $key, $data, 'swift_api', 15 * MINUTE_IN_SECONDS );
    }
    $response = rest_ensure_response( $data );
    $response-&gt;header( 'Cache-Control', 'public, max-age=300, s-maxage=900' );
    return $response;
}

// Bust on product save so editors never wait for expiry.
add_action( 'woocommerce_update_product', function ( $product_id ) {
    $product = wc_get_product( $product_id );
    foreach ( [ 'USD', 'EUR', 'GBP' ] as $cur ) {
        wp_cache_delete( 'swift_price_' . md5( $product-&gt;get_sku() . $cur ), 'swift_api' );
    }
} );
</code></pre>
<p>Avoid transients for high-volume keys when there is no object cache: each one becomes a row in <code>wp_options</code>, and if a plugin sets them with autoload on, they get loaded on every page view. That single mistake is behind a surprising share of the slow sites we see in our <a href="https://swiftwebdev.com/services/website-maintenance-support/">maintenance and support</a> work.</p>
<h3>Outbound calls without blocking the page</h3>
<p>Never call an external API inside <code>save_post</code> or during checkout with no timeout. Use <code>wp_remote_post()</code> with an explicit <code>timeout</code> of 5 to 10 seconds, queue it through Action Scheduler, and log the response code. Replace WP-Cron with a real cron entry (<code>define( 'DISABLE_WP_CRON', true )</code> plus <code>*/5 * * * * wp cron event run --due-now</code>) so queued jobs run on a schedule instead of only when a visitor arrives. For a worked example on the commerce side, see our guide to <a href="https://swiftwebdev.com/blog/integrate-third-party-crm-with-woocommerce/">integrating a third party CRM with WooCommerce</a>.</p>
<h2>Testing and monitoring the integration</h2>
<p>Before anything goes live we exercise every route from the command line with a real Application Password:</p>
<pre><code class="language-plaintext"># Public read
curl -s "https://example.com/wp-json/swift/v1/pricing/sku-1234?currency=EUR" | jq .

# Authenticated write with an Application Password
curl -s -u "api-bot:xxxx xxxx xxxx xxxx xxxx xxxx" \
  -H "Content-Type: application/json" \
  -X POST "https://example.com/wp-json/swift/v1/leads" \
  -d '{"email":"test@example.com","source":"landing-a"}'

# Discover the schema WordPress generated from your args
curl -s -X OPTIONS "https://example.com/wp-json/swift/v1/pricing/sku-1234" | jq .endpoints[0].args
</code></pre>
<p>For regression coverage, PHPUnit with the WordPress test suite lets you build a <code>WP_REST_Request</code>, dispatch it through <code>rest_get_server()</code> and assert on the response without HTTP. In production, hook <code>rest_request_after_callbacks</code> to log route, status and duration to your log stack (CloudWatch Logs if you are on AWS), and alert when the 5xx rate or p95 latency moves. Rate limit public write routes at the edge or with a small transient counter keyed on IP and route.</p>
<h2>The mistakes we fix most often in audits</h2>
<ul>
<li>Routes with <code>permission_callback</code> set to <code>__return_true</code> on write methods “because the mobile app needs it”.</li>
<li>Endpoints that return <code>get_post_meta( $id )</code> with no field list, leaking internal keys and sometimes personal data.</li>
<li>External API calls made synchronously inside page requests, with the default timeout, so a slow partner makes checkout hang.</li>
<li>Secrets stored in <code>wp_options</code> in plain text. Put them in environment variables or <code>wp-config.php</code> constants outside the web root.</li>
<li>Business logic bolted onto <code>admin-ajax.php</code>, which loads all of the admin bootstrap and cannot be cached.</li>
<li>No idempotency on webhooks, so a provider retry creates duplicate orders or leads.</li>
</ul>
<p>Cleaning these up is usually a one to two week engagement and often improves site speed as a side effect. When the integration touches WooCommerce order data, our <a href="https://swiftwebdev.com/services/woocommerce-crm-integration/">WooCommerce CRM integration</a> service covers the commerce-specific hooks and order status mapping.</p>
<h2>When to do this yourself vs hire someone</h2>
<p>A single read-only endpoint with a permission callback and a transient is a good afternoon’s work for any WordPress developer, and you should do it in-house. Hire when the custom REST API integration for WordPress involves writes from external systems, money, personal data, or an SLA. Those projects need signed webhooks, background queues, retries, logging and a rollback plan, and the cost of getting one of those wrong (duplicate charges, leaked customer data, a partner cutting you off for hammering their API) is far higher than the cost of a senior engineer building it properly the first time.</p>
<h2>Get your integration scoped</h2>
<p>Tell us what needs to talk to what, roughly how much traffic it carries and what happens when it fails, and we will come back within 24 hours with a fixed scope and fixed price in writing for your <a href="https://swiftwebdev.com/services/custom-rest-api-integration/">custom REST API integration for WordPress</a>. You work directly with the engineers who write and test the code. Start the conversation through our <a href="https://swiftwebdev.com/contact/">contact page</a>.</p>
<hr />
<p><em>Originally published at</em> <a href="https://swiftwebdev.com/blog/custom-rest-api-integration-wordpress-guide/"><em>swiftwebdev.com</em></a><em>. I build custom WordPress and WooCommerce sites and free WordPress plugins at</em> <a href="https://swiftwebdev.com"><em>Swift Web Dev</em></a><em>.</em></p>
]]></content:encoded></item></channel></rss>