Google Tag Manager
True\GoogleTagManager renders the small gtag('event', …) snippets that Google Tag Manager expects for common eCommerce milestones — product views, cart adds, checkout starts, and purchases — without you having to remember the exact key names each time.
Emitting an event
Build the data array for the event, then echo the script the class returns:
use True\GoogleTagManager;
$gtm = new GoogleTagManager;
echo $gtm->event('view_item', [
'name' => 'Product Name',
'partNumber' => '12345',
'price' => 29.99,
'brand' => 'Brand Name',
'category' => 'Category Name',
'variant' => 'Color: Red',
'quantity' => 1,
]);
Produces:
<script>
gtag("event", "view_item", {
"name": "Product Name",
"partNumber": "12345",
"price": 29.99,
"brand": "Brand Name",
"category": "Category Name",
"variant": "Color: Red",
"quantity": 1
});
</script>
Supported events
| Event | Fire it when… |
|---|---|
view_item | User views a product page. |
add_to_cart | User adds a product to their cart. |
view_cart | User opens the cart page. |
begin_checkout | User starts the checkout flow. |
login | User completes a login. |
purchase | User completes a purchase (typically on the thank-you page). |
Common data keys
Different events expect different shapes — the GTM docs are authoritative, but these are the keys the class plumbs through most often:
| Key | Type | Purpose |
|---|---|---|
name | string | Product name. |
partNumber | string | SKU / part number. |
price | float | Unit price. |
brand | string | Brand. |
category | string | Category name. |
variant | string | Variant descriptor (color, size, …). |
quantity | int | Number of items. |
Where to render it
Drop the output inline at the point in your template that corresponds to the user action:
view_item— inside the product page template.add_to_cart— inside the partial that runs after a successful cart-add (or echo it as part of a JSON response your front-end injects).purchase— inside the thank-you page, after the order is confirmed.
Your base GTM container snippet still needs to be installed in the layout — the class only handles the per-event payload, not the bootstrap.