Google Tag Manager Setup | OpsBlu Docs

Google Tag Manager Setup

Step-by-step Google Tag Manager installation and configuration guide for osCommerce.

Overview

Google Tag Manager (GTM) provides a centralized platform to manage all your tracking tags without modifying code for each change:

  • One container for all tracking codes
  • No code deployment for tag updates
  • Version control with rollback capability
  • Preview mode for testing before publishing
  • Built-in templates for GA4, Meta Pixel, and more

Prerequisites

  1. GTM Account created - Create GTM Account
  2. Container created - Get Container ID (GTM-XXXXXX)
  3. FTP/File access - To modify OSCommerce templates
  4. Backup - Complete site backup before modifications

Step 1: Create GTM Container

  1. Go to Google Tag Manager
  2. Click Create Account
  3. Account Name: Your business name
  4. Container Name: Your website domain
  5. Target Platform: Web
  6. Click Create

Copy your Container ID (format: GTM-XXXXXX)

Step 2: Install GTM Code in OSCommerce

GTM requires two code snippets: one in <head> and one in <body>.

OSCommerce 2.3.x Installation

File: catalog/includes/header.php

Add in the <head> section, as high as possible:

<head>
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');</script>
<!-- End Google Tag Manager -->

<!-- Rest of head content -->
</head>

Add immediately after the opening <body> tag:

<body>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->

<!-- Rest of body content -->

Replace GTM-XXXXXX with your actual Container ID.

OSCommerce 2.4.x Installation

File: catalog/includes/modules/header_tags/ht_google_tag_manager.php

Create a new module file:

<?php
class ht_google_tag_manager {
  var $code = 'ht_google_tag_manager';
  var $group = 'header_tags';
  var $title;
  var $description;
  var $sort_order;
  var $enabled = false;

  function __construct() {
    $this->title = 'Google Tag Manager';
    $this->description = 'Add Google Tag Manager container to all pages';
    $this->sort_order = 50;
    $this->enabled = (defined('MODULE_HEADER_TAGS_GTM_STATUS') && MODULE_HEADER_TAGS_GTM_STATUS == 'True');
  }

  function execute() {
    global $oscTemplate;

    if ($this->enabled) {
      $container_id = MODULE_HEADER_TAGS_GTM_CONTAINER_ID;

      // Head script
      $gtm_head = <<<EOD
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','{$container_id}');</script>
<!-- End Google Tag Manager -->
EOD;

      $oscTemplate->addContent($gtm_head, $this->group);

      // Body noscript (add to page content)
      $gtm_body = <<<EOD
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id={$container_id}"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
EOD;

      $oscTemplate->addContent($gtm_body, 'content_top');
    }
  }

  function isEnabled() {
    return $this->enabled;
  }

  function check() {
    return defined('MODULE_HEADER_TAGS_GTM_STATUS');
  }

  function install() {
    tep_db_query("INSERT INTO configuration (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) VALUES ('Enable Google Tag Manager', 'MODULE_HEADER_TAGS_GTM_STATUS', 'True', 'Enable Google Tag Manager?', '6', '1', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
    tep_db_query("INSERT INTO configuration (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) VALUES ('GTM Container ID', 'MODULE_HEADER_TAGS_GTM_CONTAINER_ID', '', 'Enter your GTM Container ID (GTM-XXXXXX)', '6', '2', now())");
  }

  function remove() {
    tep_db_query("DELETE FROM configuration WHERE configuration_key IN ('" . implode("', '", $this->keys()) . "')");
  }

  function keys() {
    return array('MODULE_HEADER_TAGS_GTM_STATUS', 'MODULE_HEADER_TAGS_GTM_CONTAINER_ID');
  }
}
?>

Then install via admin:

Admin > Modules > Header Tags > Install Module > Google Tag Manager

OSCommerce CE Installation

File: catalog/includes/header.php

Add GTM code the same way as 2.3.x version.

Step 3: Verify Installation

Method 1: View Page Source

  1. Visit your store homepage
  2. Right-click > View Page Source
  3. Search (Ctrl+F) for GTM-
  4. Verify your Container ID appears twice (head and body)

Method 2: Browser Console

// Open console (F12) and type:
dataLayer
// Should return an array

typeof google_tag_manager
// Should return "object"

Object.keys(google_tag_manager)
// Should show your container ID

Method 3: Network Tab

F12 > Network tab > Filter by "gtm.js"

Should see request to googletagmanager.com/gtm.js?id=GTM-XXXXXX

Step 4: Set Up GTM Preview Mode

Test your installation:

  1. In GTM, click Preview (top right)
  2. Enter your store URL
  3. Click Connect
  4. New debug window opens showing tag status

You should see:

  • Container Loaded - GTM is working
  • Tags Fired - Which tags have fired
  • Variables - Available data

Step 5: Configure Basic Data Layer

For enhanced tracking, initialize dataLayer with page info.

File: catalog/includes/header.php

Add BEFORE the GTM code:

<script>
window.dataLayer = window.dataLayer || [];
dataLayer.push({
  'pageType': '<?php echo basename($_SERVER['PHP_SELF'], '.php'); ?>',
  'userStatus': '<?php echo (tep_session_is_registered('customer_id') ? 'logged_in' : 'guest'); ?>'
  <?php if (isset($_SESSION['currency'])): ?>
  ,'currency': '<?php echo $_SESSION['currency']; ?>'
  <?php endif; ?>
  <?php if (tep_session_is_registered('customer_id')): ?>
  ,'userId': '<?php echo $customer_id; ?>'
  <?php endif; ?>
});
</script>

Then add the GTM head code.

Common GTM Tags for OSCommerce

Tag 1: Google Analytics 4

In GTM:

  1. Tags > New
  2. Tag Configuration > Google Analytics: GA4 Configuration
  3. Measurement ID: G-XXXXXXXXXX
  4. Triggering: All Pages
  5. Save

Tag 2: Meta Pixel Base Code

  1. Tags > New
  2. Tag Configuration > Custom HTML
  3. Paste Meta Pixel code:
    <script>
    !function(f,b,e,v,n,t,s)
    {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
    n.callMethod.apply(n,arguments):n.queue.push(arguments)};
    if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
    n.queue=[];t=b.createElement(e);t.async=!0;
    t.src=v;s=b.getElementsByTagName(e)[0];
    s.parentNode.insertBefore(t,s)}(window, document,'script',
    'https://connect.facebook.net/en_US/fbevents.js');
    fbq('init', 'YOUR_PIXEL_ID');
    fbq('track', 'PageView');
    </script>
    
  4. Triggering: All Pages
  5. Save

Tag 3: GA4 Pageview (if not automatic)

  1. Tags > New
  2. Tag Configuration > Google Analytics: GA4 Event
  3. Configuration Tag: Select your GA4 Config tag
  4. Event Name: page_view
  5. Triggering: All Pages
  6. Save

GTM Variables Setup

Configure variables to capture OSCommerce data.

Variable 1: Page Type

  1. Variables > User-Defined Variables > New
  2. Variable Configuration > Data Layer Variable
  3. Data Layer Variable Name: pageType
  4. Name: DLV - Page Type
  5. Save

Variable 2: User Status

  1. Variables > New
  2. Data Layer Variable
  3. Data Layer Variable Name: userStatus
  4. Name: DLV - User Status
  5. Save

Variable 3: User ID

  1. Variables > New
  2. Data Layer Variable
  3. Data Layer Variable Name: userId
  4. Name: DLV - User ID
  5. Save

GTM Triggers Setup

Trigger 1: Product Page View

  1. Triggers > New
  2. Trigger Configuration > Page View
  3. This trigger fires on: Some Page Views
  4. Fire this trigger when:
    • Page Path contains product_info.php
  5. Name: Page View - Product
  6. Save

Trigger 2: Checkout Pages

  1. Triggers > New
  2. Page View
  3. Some Page Views
  4. Fire when:
    • Page Path contains checkout
  5. Name: Page View - Checkout
  6. Save

Trigger 3: Purchase Success

  1. Triggers > New
  2. Page View
  3. Some Page Views
  4. Fire when:
    • Page Path contains checkout_success.php
  5. Name: Page View - Purchase Success
  6. Save

Publishing Your Container

  1. Click Submit (top right)
  2. Version Name: "Initial GTM Setup for OSCommerce"
  3. Version Description: "Added GA4, Meta Pixel, basic dataLayer"
  4. Click Publish

Your tags are now live!

Testing GTM Installation

Checklist

  • GTM code appears in page source (head and body)
  • dataLayer exists in console
  • google_tag_manager object exists
  • GTM Preview mode connects successfully
  • GA4 Configuration tag fires on all pages
  • Meta Pixel fires on all pages
  • Variables populate correctly
  • No JavaScript errors in console

Common Issues

Issue 1: GTM Container Not Loading

Solutions:

  1. Verify Container ID is correct
  2. Check for JavaScript errors
  3. Clear browser cache
  4. Check file permissions on header.php

Issue 2: dataLayer Not Defined

Solutions:

  1. Ensure dataLayer initialization comes BEFORE GTM code
  2. Check for syntax errors in dataLayer.push
  3. Verify proper PHP tag closures

Issue 3: Tags Not Firing in Preview Mode

Solutions:

  1. Check trigger conditions
  2. Verify page matches trigger criteria
  3. Check for ad blockers
  4. Review GTM debug console errors

Issue 4: Duplicate Tags

Solutions:

  1. Remove old hard-coded tracking (GA, Meta Pixel)
  2. Check for multiple GTM containers
  3. Review all header/footer files for duplicate code

Best Practices

1. Remove Direct Tracking Code

After GTM is working, remove:

  • Direct GA4 code from header.php
  • Direct Meta Pixel code
  • Any other direct tracking scripts

Manage everything through GTM instead.

2. Use Consistent Naming

Tags: "GA4 - Event - Add to Cart"
Triggers: "Event - Add to Cart"
Variables: "DLV - Product Name"

3. Add Descriptions

Document what each tag/trigger/variable does for future reference.

4. Use Folders

Organize tags by type:

  • Google Analytics
  • Meta Pixel
  • Utilities
  • Third-party tags

5. Test Before Publishing

Always use Preview mode before publishing changes.

6. Version Control

Use descriptive version names and descriptions for easy rollback.

Advanced Configuration

Custom JavaScript Variables

Create variables to extract data from the page:

Variable: Product ID from URL

  1. Variables > New
  2. Custom JavaScript
  3. Code:
    function() {
      var params = new URLSearchParams(window.location.search);
      return params.get('products_id');
    }
    
  4. Name: JS - Product ID

Debug Mode

Enable GTM debug in console:

// Enable debug
window.gtmDebug = true;

// View dataLayer pushes
dataLayer.push = new Proxy(dataLayer.push, {
  apply: function(target, thisArg, args) {
    console.log('dataLayer.push:', args);
    return target.apply(thisArg, args);
  }
});

Server-Side GTM (Advanced)

For enhanced privacy and tracking reliability, consider Server-Side GTM:

  1. Set up GTM Server container
  2. Configure server in Google Cloud/other provider
  3. Point OSCommerce to server endpoint
  4. Benefits: Better data control, bypasses ad blockers, improved accuracy

Next Steps

Additional Resources