---
title: WooCommerce tracking pixel instructions
slug: woocommerce-tracking-pixel-instructions
description: Install Roster's link and order tracking pixels on WooCommerce to accurately attribute ambassador clicks and referred orders.
docTags: 
createdAt: 2024-12-04T21:05:44.295Z
---

When following these steps, some brands' developers have found it helpful to first review the [Generic tracking pixel instructions](docId\:K-Bu-jEO2SM5-2G7lpO9G) and then comparing with the WooCommerce-specific instructions in this guide.&#x20;

This guide will walk you through the steps to install Roster's two tracking pixels, both of which are required to enable roster's sales attribution features, such as link tracking and referral commissions.&#x20;

:::hint{type="warning"}
## Google Tag Manager

We strongly discourage installing Roster's tracking pixels through Google Tag Manager (GTM). More and more browsers and extensions block GTM from loading, thereby blocking Roster's tracking pixels from working.&#x20;

We recommend installing Roster's tracking pixels directly in your e-commerce platform or website's global theme/template.&#x20;
:::

***

## Step 1: Get a public access API token

Each of the two tracking pixels require a public access token in order to securely send tracking data from a customer's browser to your Roster account. You can use the same public access token for both tracking pixels.

::::WorkflowBlock
:::WorkflowBlockItem
Log into your Roster account.
:::

:::WorkflowBlockItem
Go to the API integration page by clicking on your brand's name in the left-hand navigation, then `Integrations` > `API integration`

![](https://api.archbee.com/api/optimize/mmAK_JBzN5YWZNnNvmD7r/umEJyWiyZ6TIWAeQIp6gM_cleanshot-2025-02-03-at-125959.png)
:::

:::WorkflowBlockItem
Copy the newest Public Access Token if one exists, or click New Access Token to create a new one.

![](https://api.archbee.com/api/optimize/mmAK_JBzN5YWZNnNvmD7r/V-F_SKIGoTC4MA-pYmNIM_cleanshot-2025-02-03-at-130154.png)
:::
::::



:::hint{type="warning"}
Never use Private Access Tokens with Roster's tracking pixels. Public Access Tokens are safe to use in a browser environment, but Private Access Tokens are only intended for server-side usage as they allow full access to all Roster API endpoints.
:::

***

## Step 2: Install the link tracking pixel

Roster's link tracking pixel tracks link clicks from ambassadors' referral links and stores ambassadors' referral link IDs in the browser to track subsequent purchases.&#x20;

:::hint{type="info"}
Ensure the person performing the following steps has admin access to your WooCommerce account.
:::

:::::WorkflowBlock
:::WorkflowBlockItem
Log into your WooCommerce account.&#x20;
:::

:::WorkflowBlockItem
Open the editor for `header.php` by navigating to `Appearance` > `Theme Editor` > `header.php`
:::

:::WorkflowBlockItem
Paste the following Javascript tags just before the closing `</head>` tag.

```javascript
<script type="text/javascript">
  window.roster = {
    config: {
      token: 'PUBLIC_ACCESS_TOKEN',
      forceShareableCodeFetch: true
    },
    onClickTracked: function() {
      // Optional callback. See table below for details.
      console.log('Click tracked');
    },
    onCodeRetrieved: function(discountCode) {
      // Optional callback. See table below for details.
      console.log('Discount code:', discountCode);
    },
    onError: function(error) {
      // Optional callback. See table below for details.
      console.error('Roster pixel error:', error);
    }
  };
</script>

<script async type="application/javascript"
  src="https://cdn.rostercdn.com/sa.js"></script>
```
:::

:::WorkflowBlockItem
Replace PUBLIC\_ACCESS\_TOKEN in the Javascript tag with the Public Access Token from `Step 1` above.&#x20;
:::

::::WorkflowBlockItem
Verify the link trakcing pixel

After your have published the changes to your storefront or website, verify that link tracking is working by using an ambassador's referral link from your Roster account.&#x20;

:::hint{type="info"}
See [Verify installation with Roster's Chrome Extension](docId:-J9KDLPJTCpDKR6ebLFWz) to speed up the verification process using Roster's Chrome browser extension.
:::
::::
:::::

***

## Step 3: Install the order tracking pixel

Roster's order tracking pixel is an order-aware Javascript pixel that needs to be installed on the order confirmation page (the page that loads immediately after a customer completes a purchase.)&#x20;

Install the order tracking pixel using one of the following two options.

:::hint{type="info"}
Refer to this [article](https://woocommerce.github.io/code-reference/classes/WC-Order.html) for more details on the WC\_Order object.
:::

### Option 1: Add tracking to `thankyou.php` (Recommended)

We recommended adding the order tracking pixel directly to the `thankyou.php` file based on feedback from other brands using WooCommerce.&#x20;

::::WorkflowBlock
:::WorkflowBlockItem
Open your theme's `thankyou.php` file in an editor
:::

:::WorkflowBlockItem
Locate your theme's `thankyou.php` file.

- If using a default theme, it is usually be found here: `wp-content/plugins/woocommerce/templates/checkout/thankyou.php`
- If using a custom WooCommerce theme, it is usually be found here: `/themes/your_custom_theme/woocommerce/checkout/thankyou.php`
:::

:::WorkflowBlockItem
Locate the following line of code in `thankyou.php`

```javascript
<?php do_action( 'woocommerce_thankyou', $order->get_id() ); ?>
```
:::

:::WorkflowBlockItem
Paste the following Javascript tag just below the line of code you found in the previous step:

```javascript
<!-- Roster Order Submission: START -->
<script type='application/javascript'>
function submitOrder() {
  if (sAttribution) {
    var totalPrice = <?php echo $order->get_subtotal(); ?>;
    var discount_total = <?php echo $order->get_total_discount(); ?> ?? 0;
    var subTotal = totalPrice - discount_total;

    sAttribution.set({
      orderId: "<?php echo $order->get_id(); ?>",
      orderDate: "<?php echo $order->get_date_created(); ?>",
      discountCodes: <?php echo json_encode($order->get_coupon_codes()); ?>,
      currency: "<?php echo $order->get_currency(); ?>",
      subtotalPrice: subTotal,
      totalPrice: <?php echo $order->get_total(); ?>,
      firstName: "<?php echo $order->get_billing_first_name(); ?>",
      lastName: "<?php echo $order->get_billing_last_name(); ?>",
      email: "<?php echo $order->get_billing_email(); ?>"
    });
    sAttribution.emitOrder();
  }
}
var saScript = document.createElement("script");
saScript.addEventListener("load", submitOrder);
saScript.src = "https://sa.getroster.com/sa.js?token=PUBLIC_ACCESS_TOKEN";
document.body.appendChild(saScript);
</script>
<!-- Roster Order Submission: END -->
```
:::

:::WorkflowBlockItem
Replace `PUBLIC_ACCESS_TOKEN` in the Javascript tag with the Public Access Token from `Step 1` above.&#x20;
:::
::::

### Option 2: Add tracking to `functions.php`

With this option, you will add the order tracking pixel to `functions.php`

:::::WorkflowBlock
:::WorkflowBlockItem
Log into your WooCommerce account.&#x20;
:::

::::WorkflowBlockItem
Open the editor for `functions.php` by navigating to `Appearance` > `Theme Editor` > `functions.php`

:::hint{type="info"}
If using a custom theme, ensure the custom theme is selected in the `Select theme to edit` dropdown.
:::
::::

:::WorkflowBlockItem
Back up the current `functions.php` by copying and pasting it into an editor on your desktop and saving it for future reference.
:::

:::WorkflowBlockItem
Paste the following PHP code at the end of `functions.php`

```php
/**
* Add Roster analytics code to the thank-you page
* Ref: https://docs.woocommerce.com/wc-apidocs/class-WC_Order.html
*/
add_action( 'woocommerce_thankyou', 'roster_attribution' );

function roster_attribution( $order_id ) {
$order = wc_get_order( $order_id );

if ( $order ) {
$usedCoupons = json_encode($order->get_used_coupons());

echo "<!-- Roster Order Submission: START -->
<script type='application/javascript'>
function submitOrder() {
  if (sAttribution) {
    var totalPrice = {$order->get_subtotal()};
    var discount_total = {$order->get_total_discount()} ?? 0;
    var subTotal = totalPrice - discount_total;

    sAttribution.set({
    orderId: \"{$order_id}\",
    orderDate: \"{$order->get_date_created()}\", 
    discountCodes: {$usedCoupons},
    currency: \"{$order->get_currency()}\",
    subtotalPrice: subTotal, 
    totalPrice: {$order->get_total()},
    firstName: \"{$order->get_billing_first_name()}\",
    lastName: \"{$order->get_billing_last_name()}\",
    email: \"{$order->get_billing_email()}\"
  });
  
  sAttribution.emitOrder();
  }
}

var saScript = document.createElement(\"script\");
saScript.addEventListener(\"load\", submitOrder);
saScript.src = \"https://sa.getroster.com/sa.js?token=ACCESS_TOKEN\";
document.body.appendChild(saScript );
</script>
<!-- Roster Order Submission: END -->";
}
}
```
:::

:::WorkflowBlockItem
Replace `ACCESS_TOKEN` in the Javascript tag with the Public Access Token from `Step 1` above.&#x20;
:::
:::::

***

## Step 4: Verify the installation process

It's imperative that you test the link tracking and order tracking upon completing the above steps.&#x20;

See [Verify tracking pixel installation](docId\:hSZdrYDoQ2cmTKv8CXbWP) for a video walkthrough and detailed steps and [Verify installation with Roster's Chrome Extension](docId:-J9KDLPJTCpDKR6ebLFWz).

***

## Event reference for link tracking pixel

| Callback          | Signature                | Description                                                                                                                                                                                                                                                                                                   |
| ----------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `onCodeRetrieved` | `function(discountCode)` | Called when a discount code is successfully returned from Roster's shareable endpoint. `discountCode` is a string containing the code to apply.                                                                                                                                                               |
| `onClickTracked`  | `function(click)`        | Called when a referral click is tracked by the pixel. `click` is an object containing click details such as `referralLinkId`, `landingPageUrl`, `referrerUrl`, `queryParams`, `utmParams`, `userAgent`, `linkSource`, `linkVariant`, `characterSet`, `title`, `location`, `externalId`, and `clickTimestamp`. |
| `onError`         | `function(error)`        | Called when an error occurs during the shareable endpoint request or a callback error is caught. `error` is a string or Error object describing what went wrong.                                                                                                                                              |

***

## Config reference for link tracking pixel

| Property                  | Type      | Default | Description                                                                                                |
| ------------------------- | --------- | ------- | ---------------------------------------------------------------------------------------------------------- |
| `token`                   | `string`  | `""`    | Your public access API token. Required.                                                                    |
| `forceShareableCodeFetch` | `boolean` | `false` | Set to `true` to enable discount code retrieval on non-Shopify storefronts. Required for this integration. |

***

##

***

## Need help?

If you have any questions about adding hidden products to product rewards, contact us at [support@getroster.com](mailto\:support@getroster.com).

