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

EventFire it when…
view_itemUser views a product page.
add_to_cartUser adds a product to their cart.
view_cartUser opens the cart page.
begin_checkoutUser starts the checkout flow.
loginUser completes a login.
purchaseUser 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:

KeyTypePurpose
namestringProduct name.
partNumberstringSKU / part number.
pricefloatUnit price.
brandstringBrand.
categorystringCategory name.
variantstringVariant descriptor (color, size, …).
quantityintNumber 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.