Developer / API
Composer package: yui/craft-ga-analytics. Plugin handle / translation category: gaanalytics.
Namespace root: yui\gaanalytics.
Twig API: craft.serverAnalytics
Registered as the serverAnalytics Craft variable (AnalyticsVariable).
| Method | Returns | Purpose |
|---|---|---|
pageViewEvent(url = '', title = '') | PageViewEvent | Build a page-view event object for the current source, defaulting the URL/title from the request if omitted. |
simpleEvent(eventName = '') | BaseEvent | Build a generic named GA4 event you can attach parameters to. |
ga4() | the GA4 analytics client | Low-level access to the underlying analytics client used to queue/send events. |
pageViewTrackingUrl(url, title) | Twig\Markup (raw string) | A tracking-pixel/beacon URL for a page view, for use in <img> tags or non-JS contexts. |
eventTrackingUrl(url, eventName = '', params = []) | Twig\Markup (raw string) | Same as above for a named event with custom parameters. |
api(attributes = null) | ReportRequestCriteria | Build a GA4 Data API report request (dimensions, metrics, date range) to run against a source. |
Events built with simpleEvent()/pageViewEvent() support fluent setParam()/typed setters
(see Event classes below) before being queued; queued events are actually sent
on Response::EVENT_AFTER_SEND, so building an event doesn't block the response.
pageViewTrackingUrl() and eventTrackingUrl() return Twig\Markup pointing at the plugin's own
site-facing tracking routes (instantanalytics/pageViewTrack,
instantanalytics/eventTrack/<filename>), so an event can be recorded from a plain <img>/<a>
without any JS — useful for email templates or non-JS clients.
Automatic event wiring
Plugin::installSiteEventListeners() hooks into Craft/yStore events and forwards them to GA4 —
no template changes are required for these once the corresponding event is enabled under
Google Analytics Data Types in settings (Settings):
| Craft/yStore event | GA4 event |
|---|---|
View::EVENT_AFTER_RENDER_PAGE_TEMPLATE (non-AJAX) | page_view |
CustomerService::EVENT_AFTER_CUSTOMER_LOGIN | login |
CustomerService::EVENT_AFTER_CUSTOMER_SIGN_UP | sign_up |
SearchService::EVENT_AFTER_SEARCH | search |
CartService::EVENT_AFTER_CART_VIEW | view_cart |
Products::EVENT_AFTER_PRODUCT_VIEW | view_item |
CartService::EVENT_AFTER_ADD_TO_CART | add_to_cart |
CartService::EVENT_AFTER_REMOVE_FROM_CART | remove_from_cart |
CheckoutService::EVENT_AFTER_BEGIN_CHECKOUT | begin_checkout |
CheckoutService::EVENT_AFTER_PURCHASE_SUCCESS | purchase (transaction ID, value, tax, shipping, coupon, and each line item) |
These listeners are only registered when yStore (yui/craft-plugin) is installed and enabled;
Plugin::$shopPlugin is checked at Plugins::EVENT_AFTER_LOAD_PLUGINS before wiring them up.
Event classes
Every outgoing GA4 event is a small model under yui\gaanalytics\events, extending
base\events\BaseEvent (or ItemBaseEvent for events with a cart/order item list):
PageViewEvent, LoginEvent, SignUpEvent, SearchEvent, ViewItemEvent, ViewCartEvent,
AddToCartEvent, RemoveFromCartEvent, BeginCheckoutEvent, PurchaseEvent. Each has typed
get*()/set*() methods for its GA4 parameters (e.g. PurchaseEvent::setTransactionId(),
setValue(), setCurrency(), setCoupon(), setShipping(), setTax()) and validates required
fields before it's sent — building one with a missing required parameter throws
yui\gaanalytics\errors\ValidationException.
Data model
Source(models\Source,records\Source) — a connected GA4 property: name, GA4 property ID/measurement ID, OAuth account reference.SiteSource(models\SiteSource,records\SiteSource) — maps a CraftsiteIdto asourceId. Look one up withAnalytics::$plugin->getSources()->getSiteSourceBySiteId($siteId).ReportRequestCriteria— the model built bycraft.serverAnalytics.api()/ used internally to call the GA4 Data API; carries dimensions, metrics, and a date range.
Access the plugin's services from PHP via the Analytics::$plugin singleton
(yui\gaanalytics\Plugin), e.g. Analytics::$plugin->getSources(), ->getOauth(),
->getReports(), ->getCache(), ->getLicense().
Analytics Report field type
fields\Report (display name "Analytics Report") renders a small GA4 report scoped to the
owning element's mapped SiteSource. It degrades to a placeholder template instead of erroring
when the field type is disabled in settings, the plugin isn't fully configured, or the element's
site has no mapped source — check fields/Report.php before assuming the field always renders
live data.
Dashboard widgets
Three craft\base\Widget implementations, registered on Dashboard::EVENT_REGISTER_WIDGET_TYPES:
widgets\Realtime (active users; only selectable when Enable real-time reporting is on),
widgets\Report (configurable chart against any GA4 dimension/metric for a source and period),
and widgets\Ecommerce (revenue/average order/conversion summary; requires yStore data). All
three check enableWidgets/enableRealtime in settings and the plugin's connection state before
rendering, falling back to "not connected"/"disabled" partials otherwise.
MCP tools
Registered on \yui\mcp\Plugin::EVENT_REGISTER_TOOLS when yui/craft-mcp is installed. All tools
extend mcp\AbstractGaAnalyticsTool and accept an optional source_id (defaults to the first
configured source):
| Tool | Description | Extra parameters |
|---|---|---|
analytics_realtime | Active users, pageviews/min (last 30 min), top active pages. | — |
analytics_ecommerce | Total revenue, transactions, revenue/transactions per user for a period. | period: week | month | year (default week) |
analytics_geo | Sessions/users by geography for a period. | period (default month), dimension: country | continent | region | city (default country) |
analytics_report | Generic GA4 report with custom metrics/dimensions for a date range. | metrics (comma-separated GA4 metric names), dimensions (optional, comma-separated) |
CP routes worth knowing about
| Route | Purpose |
|---|---|
gaanalytics/sources | List/manage GA4 Sources |
gaanalytics/sources/new, gaanalytics/sources/<sourceId> | Add/edit a Source |
gaanalytics/sites | Map Craft sites to Sources |
gaanalytics/wizard, gaanalytics/wizard/settings | First-run setup wizard |
gaanalytics/settings, gaanalytics/settings/oauth | Plugin settings and OAuth connection |
gaanalytics/tests/* | Diagnostic pages (formatting, template variables, live GA4/GA4-metadata calls) |
gaanalytics/license and children | License activation/redemption panel |
instantanalytics/pageViewTrack, instantanalytics/eventTrack/<filename> | Anonymous site-facing tracking endpoints used by the Twig tracking-URL helpers |
Every route above except the two instantanalytics/* tracking endpoints requires a CP request.
Caching
GA4 Data API responses are cached through services\Cache when Enable Cache is on, keyed by
call + arguments, for Cache Duration (a PHP DateInterval string, default PT10M). Disable
caching only for debugging — GA4 enforces per-property request quotas, and dashboard widgets +
the Report field can otherwise issue several report calls per page load.