Overview
Google Analytics 4 (GA4) provides comprehensive analytics for your OSCommerce store, including:
- Real-time visitor tracking
- Ecommerce conversion tracking
- Product performance analytics
- Customer journey analysis
- Marketing attribution
- Revenue tracking
Prerequisites
Before starting:
- GA4 Property created - Create GA4 Property
- Measurement ID - Format:
G-XXXXXXXXXX - FTP/File access - To modify OSCommerce template files
- Backup - Complete site backup before modifications
Installation Method
OSCommerce requires manual code modifications to install GA4. There are no modern extensions available.
Step 1: Locate Template Files
OSCommerce template location depends on your version:
OSCommerce 2.3.x:
includes/header.php
includes/footer.php
OSCommerce 2.4.x:
includes/templates/[your_template]/header.php
includes/templates/[your_template]/footer.php
OSCommerce CE:
includes/modules/header_tags/ht_google_analytics.php (if exists)
Or: catalog/includes/header.php
Step 2: Add GA4 Base Code to Header
File: includes/header.php (or equivalent)
Add this code before the closing </head> tag:
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX', {
'send_page_view': true
});
</script>
Replace G-XXXXXXXXXX with your actual Measurement ID.
Step 3: Verify Installation
- Visit your store in a browser
- Right-click > View Page Source
- Search (Ctrl+F) for
gtag - Verify the Measurement ID is correct
Step 4: Test with GA4 DebugView
Enable debug mode for testing:
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX', {
'send_page_view': true,
'debug_mode': true // Enable debug mode
});
</script>
Check DebugView:
Google Analytics > Admin > DebugView
You should see real-time events within seconds.
OSCommerce Version-Specific Instructions
OSCommerce 2.3.x Classic
File: catalog/includes/header.php
Find the closing </head> tag and add GA4 code just before it:
<?php
// ... existing OSCommerce header code ...
?>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
</head>
OSCommerce 2.4.x Responsive
File: catalog/includes/modules/header_tags/ht_google_analytics.php
If this file doesn't exist, create it:
<?php
class ht_google_analytics {
var $code = 'ht_google_analytics';
var $group = 'header_tags';
var $title;
var $description;
var $sort_order;
var $enabled = false;
function __construct() {
$this->title = 'Google Analytics 4';
$this->description = 'Add GA4 tracking code to all pages';
$this->sort_order = 100;
$this->enabled = (defined('MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_STATUS') && MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_STATUS == 'True');
}
function execute() {
global $oscTemplate;
$ga4_code = '<!-- Google tag (gtag.js) -->' . "\n" .
'<script async src="https://www.googletagmanager.com/gtag/js?id=' . MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_ID . '"></script>' . "\n" .
'<script>' . "\n" .
' window.dataLayer = window.dataLayer || [];' . "\n" .
' function gtag(){dataLayer.push(arguments);}' . "\n" .
' gtag(\'js\', new Date());' . "\n" .
' gtag(\'config\', \'' . MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_ID . '\');' . "\n" .
'</script>' . "\n";
$oscTemplate->addContent($ga4_code, $this->group);
}
function isEnabled() {
return $this->enabled;
}
function check() {
return defined('MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_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 Analytics Module', 'MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_STATUS', 'True', 'Do you want to enable the Google Analytics module?', '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 ('Google Analytics Measurement ID', 'MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_ID', '', 'Enter your GA4 Measurement ID (G-XXXXXXXXXX)', '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_GOOGLE_ANALYTICS_STATUS', 'MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_ID');
}
}
?>
Then install via:
Admin > Modules > Header Tags > Install Module > Google Analytics 4
OSCommerce CE (Community Edition)
File: includes/header.php or use the module system if available.
OSCommerce CE has better support for modules, so check:
Admin > Modules > Content
If no GA4 module exists, manually add to header.php as in 2.3.x instructions.
Configuration Options
Basic Configuration
gtag('config', 'G-XXXXXXXXXX', {
'send_page_view': true, // Send automatic pageviews
'cookie_domain': 'auto', // Auto-detect cookie domain
'cookie_flags': 'SameSite=None;Secure' // Cookie settings
});
Enhanced Configuration
gtag('config', 'G-XXXXXXXXXX', {
'send_page_view': true,
'cookie_domain': 'auto',
'cookie_prefix': 'osc', // Prefix for GA cookies
'cookie_expires': 63072000, // 2 years in seconds
'anonymize_ip': false, // IP anonymization (not needed in GA4)
'allow_google_signals': true, // Enable advertising features
'allow_ad_personalization_signals': true
});
Multi-Domain Tracking
If you have multiple domains (e.g., www and non-www):
gtag('config', 'G-XXXXXXXXXX', {
'cookie_domain': '.yourdomain.com', // Note the leading dot
'linker': {
'domains': ['yourdomain.com', 'checkout.yourdomain.com']
}
});
Enhanced Ecommerce Setup
For ecommerce tracking, you'll also need to modify these files:
- Product views:
product_info.php - Add to cart:
shopping_cart.php - Checkout:
checkout_process.php
See Enhanced Ecommerce Tracking for complete implementation.
User-ID Tracking
Track logged-in customers:
File: includes/header.php
<?php
// After session start
if (tep_session_is_registered('customer_id')) {
$user_id = $customer_id;
} else {
$user_id = null;
}
?>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX', {
<?php if ($user_id): ?>
'user_id': '<?php echo tep_output_string($user_id); ?>',
<?php endif; ?>
'send_page_view': true
});
</script>
Custom Dimensions
Set up custom dimensions for OSCommerce-specific data:
In GA4:
Admin > Data display > Custom definitions > Create custom dimensions
In OSCommerce header.php:
<?php
// Get customer data
$customer_type = (tep_session_is_registered('customer_id')) ? 'Logged In' : 'Guest';
$customer_country = isset($customer_country) ? $customer_country : 'Unknown';
?>
<script>
gtag('config', 'G-XXXXXXXXXX', {
'custom_map': {
'dimension1': 'customer_type',
'dimension2': 'customer_country'
}
});
gtag('event', 'page_view', {
'customer_type': '<?php echo $customer_type; ?>',
'customer_country': '<?php echo $customer_country; ?>'
});
</script>
Exclude Admin Traffic
Prevent admin panel visits from being tracked:
File: includes/header.php
<?php
// Check if in admin area
$is_admin = (strpos($_SERVER['PHP_SELF'], '/admin/') !== false);
if (!$is_admin) {
?>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
<?php
}
?>
Or exclude by IP address in GA4:
Admin > Data Filters > Create Filter
Filter Name: Exclude Internal Traffic
Filter Type: Internal Traffic
IP addresses: [Your office IP]
Verification Steps
1. Check Real-Time Reports
Google Analytics > Reports > Realtime
Visit your store and verify:
- Active users show up
- Pageviews are tracked
- Location data appears
2. Check Page Source
# View source and search for GA4 code
1. Right-click page > View Page Source
2. Search (Ctrl+F) for: gtag
3. Verify Measurement ID is correct
3. Browser Console Check
// Open console (F12) and type:
dataLayer
// Should show array with gtag data
typeof gtag
// Should return "function"
4. Network Tab Check
F12 > Network tab > Filter by "collect"
# Should see requests to google-analytics.com/g/collect
Common Issues
Issue 1: GA4 Code Not Appearing
Problem: View source shows no gtag code
Solutions:
- Clear OSCommerce cache (if enabled)
- Check file permissions (header.php should be readable)
- Verify you edited the correct header.php file
- Check for syntax errors in PHP code
Issue 2: Tracking Code Appears Twice
Problem: Duplicate GA4 code on page
Solutions:
- Check both header.php and footer.php
- Check for multiple template files being loaded
- Search all files for your Measurement ID:
grep -r "G-XXXXXXXXXX" /path/to/oscommerce/
Issue 3: Events Not Showing in GA4
Problem: Code installed but no data in reports
Solutions:
- Wait 24-48 hours for data processing
- Check DebugView for real-time validation
- Verify Measurement ID is correct
- Check browser console for JavaScript errors
- Disable ad blockers and test
Issue 4: PHP Errors After Installation
Problem: Site breaks after adding tracking code
Solutions:
- Check for missing PHP tags (
<?php ?>) - Verify all quotes are properly escaped
- Restore from backup and try again
- Check PHP error logs for specific errors
Testing Checklist
- GA4 code appears in page source
- Measurement ID is correct
- No JavaScript errors in console
- Events appear in DebugView
- Real-time reports show activity
- Test on multiple pages (home, product, checkout)
- Test with different browsers
- Verify admin traffic is excluded