Skip to main content

Mark tag – Server side code setup

Server side code setup: Instructions for server-side code setup for MarkTag.

Rubaiyat Farhan avatar
Written by Rubaiyat Farhan
Updated over 2 months ago

Prerequisites

Before implementing MarkTag on your WordPress site, ensure you have:

  • MarkTag server-side setup completed (DNS verified)

  • Your MarkTag hostname (from the setup process)

  • WordPress admin access

  • Basic familiarity with WordPress theme editing OR a code snippet plugin

Installation Methods

Method 1: Using a Code Snippet Plugin

Step 1: Install a Code Snippet Plugin

  1. Go to PluginsAdd New in WordPress admin

  2. Search for "Code Snippets" or "Insert Headers and Footers"

  3. Install and activate the plugin

Popular Options:

  • Code Snippets - Most feature-rich

  • Insert Headers and Footers - Simplest

  • WPCode - User-friendly with a visual interface

Step 2: Add the MarkTag Base Script

  1. Go to plugin settings (e.g., SnippetsAdd New)

  2. Create a new snippet titled "MarkTag Base Script"

  3. Add this code (replace YOUR-MARKTAG-HOSTNAME with your actual hostname):

<script>
!function(w,d){
w.mtag=w.mtag||function(){(w.mtag.q=w.mtag.q||[]).push(arguments)};
var s=d.createElement('script');
s.async=true;
s.src='https://YOUR-MARKTAG-HOSTNAME/tag.js';
d.head.appendChild(s);
}(window,document);
</script>

  1. Set location to Header or Before closing </head>

  2. Save and activate the snippet

Method 2: Direct Theme Integration

Step 1: Access Theme Files

  1. Go to AppearanceTheme Editor

  2. Look for Theme Header (header.php) or Theme Functions (functions.php)

Important: Create a child theme first to preserve changes during theme updates.

Step 2: Add Base Script to Header

Option A: Add to header.php

  1. Find the </head> closing tag

  2. Add the MarkTag script just before it:

<!-- MarkTag Base Script -->
<script>
!function(w,d){
w.mtag=w.mtag||function(){(w.mtag.q=w.mtag.q||[]).push(arguments)};
var s=d.createElement('script');
s.async=true;
s.src='https://YOUR-MARKTAG-HOSTNAME/tag.js';
d.head.appendChild(s);
}(window,document);
</script>
</head>

Option B: Add to functions.php

function add_marktag_script() {
?>
<script>
!function(w,d){
w.mtag=w.mtag||function(){(w.mtag.q=w.mtag.q||[]).push(arguments)};
var s=d.createElement('script');
s.async=true;
s.src='https://YOUR-MARKTAG-HOSTNAME/tag.js';
d.head.appendChild(s);
}(window,document);
</script>
<?php
}
add_action('wp_head', 'add_marktag_script');

Basic Event Tracking

Auto-Track Page Views

Once the base script is installed, MarkTag automatically tracks page views. To enhance with user data:

<script>
// Track page view with user data (if available)
mtag('event', {
type: 'ViewContent',
email: '<?php echo wp_get_current_user()->user_email; ?>',
phone: '<?php echo get_user_meta(get_current_user_id(), "phone", true); ?>'
});
</script>

E-Commerce Events

1. View Product Page

Add to your theme's single-product.php or use a code snippet that runs on product pages:

add_action('wp_footer', 'marktag_track_add_to_cart');
function marktag_track_add_to_cart() {
?>
<script>
jQuery(document).on('click', '.single_add_to_cart_button', function() {
var productId = jQuery('input[name="product_id"]').val() || jQuery(this).val();
var quantity = jQuery('input[name="quantity"]').val() || 1;

// Get product data from page
var productData = {
type: 'AddToCart',
value: parseFloat(jQuery('.price .amount').text().replace(/[^0-9.-]+/g,"")),
currency: '<?php echo get_woocommerce_currency(); ?>',
products: [{
id: productId,
name: jQuery('.product_title').text(),
quantity: parseInt(quantity),
price: parseFloat(jQuery('.price .amount').text().replace(/[^0-9.-]+/g,""))
}]
};

mtag('event', productData);
});
</script>
<?php
}

2. Add to Cart

add_action('wp_footer', 'marktag_track_add_to_cart');
function marktag_track_add_to_cart() {
?>
<script>
jQuery(document).on('click', '.single_add_to_cart_button', function() {
var productId = jQuery('input[name="product_id"]').val() || jQuery(this).val();
var quantity = jQuery('input[name="quantity"]').val() || 1;

// Get product data from page
var productData = {
type: 'AddToCart',
value: parseFloat(jQuery('.price .amount').text().replace(/[^0-9.-]+/g,"")),
currency: '<?php echo get_woocommerce_currency(); ?>',
products: [{
id: productId,
name: jQuery('.product_title').text(),
quantity: parseInt(quantity),
price: parseFloat(jQuery('.price .amount').text().replace(/[^0-9.-]+/g,""))
}]
};

mtag('event', productData);
});
</script>
<?php
}

3. View Cart

Add to cart page template or use action hook:

add_action('woocommerce_after_cart', 'marktag_track_view_cart');
function marktag_track_view_cart() {
$cart = WC()->cart;
$current_user = wp_get_current_user();

$products = array();
foreach ($cart->get_cart() as $cart_item) {
$product = $cart_item['data'];
$products[] = array(
'id' => $product->get_sku() ?: $product->get_id(),
'name' => $product->get_name(),
'category' => strip_tags($product->get_categories()),
'quantity' => $cart_item['quantity'],
'price' => $product->get_price()
);
}
?>
<script>
mtag('event', {
type: 'ViewCart',
email: '<?php echo $current_user->user_email; ?>',
phone: '<?php echo get_user_meta($current_user->ID, "billing_phone", true); ?>',
value: <?php echo $cart->get_cart_contents_total(); ?>,
currency: '<?php echo get_woocommerce_currency(); ?>',
products: <?php echo json_encode($products); ?>
});
</script>
<?php
}

4. Begin Checkout

add_action('woocommerce_before_checkout_form', 'marktag_track_begin_checkout');
function marktag_track_begin_checkout() {
$cart = WC()->cart;
$current_user = wp_get_current_user();

$products = array();
foreach ($cart->get_cart() as $cart_item) {
$product = $cart_item['data'];
$products[] = array(
'id' => $product->get_sku() ?: $product->get_id(),
'name' => $product->get_name(),
'category' => strip_tags($product->get_categories()),
'quantity' => $cart_item['quantity'],
'price' => $product->get_price(),
'discount' => $cart_item['line_subtotal'] - $cart_item['line_total']
);
}
?>
<script>
mtag('event', {
type: 'BeginCheckout',
email: '<?php echo $current_user->user_email; ?>',
phone: '<?php echo get_user_meta($current_user->ID, "billing_phone", true); ?>',
value: <?php echo $cart->get_cart_contents_total(); ?>,
currency: '<?php echo get_woocommerce_currency(); ?>',
shipping_cost: <?php echo $cart->get_shipping_total(); ?>,
tax: <?php echo $cart->get_total_tax(); ?>,
products: <?php echo json_encode($products); ?>
});
</script>
<?php
}

5. Purchase (Order Confirmation)

add_action('woocommerce_thankyou', 'marktag_track_purchase');
function marktag_track_purchase($order_id) {
$order = wc_get_order($order_id);

$products = array();
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$products[] = array(
'id' => $product->get_sku() ?: $product->get_id(),
'name' => $product->get_name(),
'category' => strip_tags($product->get_categories()),
'quantity' => $item->get_quantity(),
'price' => $product->get_price(),
'discount' => $item->get_subtotal() - $item->get_total()
);
}
?>
<script>
mtag('event', {
type: 'Purchase',
email: '<?php echo $order->get_billing_email(); ?>',
phone: '<?php echo $order->get_billing_phone(); ?>',
value: <?php echo $order->get_total(); ?>,
currency: '<?php echo $order->get_currency(); ?>',
shipping_cost: <?php echo $order->get_shipping_total(); ?>,
tax: <?php echo $order->get_total_tax(); ?>,
transaction_id: '<?php echo $order->get_order_number(); ?>',
products: <?php echo json_encode($products); ?>
});
</script>
<?php
}

User Authentication Events

Track Login

add_action('wp_login', 'marktag_track_login', 10, 2);
function marktag_track_login($user_login, $user) {
?>
<script>
mtag('event', {
type: 'Login',
email: '<?php echo $user->user_email; ?>',
phone: '<?php echo get_user_meta($user->ID, "billing_phone", true); ?>'
});
</script>
<?php
}

Track Registration

add_action('user_register', 'marktag_track_signup');
function marktag_track_signup($user_id) {
$user = get_userdata($user_id);
?>
<script>
mtag('event', {
type: 'Signup',
email: '<?php echo $user->user_email; ?>',
phone: '<?php echo get_user_meta($user_id, "phone", true); ?>'
});
</script>
<?php
}

Lead Generation Events

Contact Form Tracking (Contact Form 7)

add_action('wpcf7_mail_sent', 'marktag_track_contact_form');
function marktag_track_contact_form($contact_form) {
$submission = WPCF7_Submission::get_instance();
$posted_data = $submission->get_posted_data();
?>
<script>
mtag('event', {
type: 'Contact',
email: '<?php echo isset($posted_data['your-email']) ? $posted_data['your-email'] : ''; ?>',
phone: '<?php echo isset($posted_data['your-phone']) ? $posted_data['your-phone'] : ''; ?>'
});
</script>
<?php
}

Lead Form Tracking (Generic)

Add to your lead form thank you page:

<script>
mtag('event', {
type: 'Lead',
email: 'captured-email@example.com', // Replace with actual email
phone: '+1234567890', // Replace with actual phone
value: 50.0, // Optional: estimated lead value
currency: 'USD'
});
</script>

Custom Event Examples

Track Search

add_action('wp_footer', 'marktag_track_search');
function marktag_track_search() {
if (is_search()) {
$current_user = wp_get_current_user();
?>
<script>
mtag('event', {
type: 'Search',
email: '<?php echo $current_user->user_email; ?>',
phone: '<?php echo get_user_meta($current_user->ID, "phone", true); ?>',
search_term: '<?php echo esc_js(get_search_query()); ?>'
});
</script>
<?php
}
}

Track Newsletter Subscription

// For MailChimp or similar
add_action('mc4wp_form_success', 'marktag_track_subscribe');
function marktag_track_subscribe($form) {
$email = $_POST['EMAIL'];
?>
<script>
mtag('event', {
type: 'Subscribe',
email: '<?php echo esc_js($email); ?>',
value: 10.0, // Monthly subscription value
currency: 'USD',
products: [{
id: 'newsletter-monthly',
name: 'Monthly Newsletter',
price: 10.0
}]
});
</script>
<?php
}

Track Social Share

<!-- Add to share buttons -->
<button onclick="shareOnFacebook()">Share on Facebook</button>

<script>
function shareOnFacebook() {
mtag('event', {
type: 'Share',
share_method: 'Facebook',
item_id: '<?php echo get_the_ID(); ?>'
});
// Your share logic here
}
</script>

Advanced Implementation Tips

1. Dynamic User Data

Create a helper function to get user data consistently:

function marktag_get_user_data() {
$current_user = wp_get_current_user();

$data = array(
'email' => '',
'phone' => ''
);

if ($current_user->ID) {
$data['email'] = $current_user->user_email;
$data['phone'] = get_user_meta($current_user->ID, 'billing_phone', true);
}

return $data;
}

Then use it in events:

$user_data = marktag_get_user_data();
mtag('event', {
type: 'ViewContent',
email: '<?php echo $user_data['email']; ?>',
phone: '<?php echo $user_data['phone']; ?>'
});

2. Conditional Event Tracking

Only track events when MarkTag is active:

function is_marktag_active() {
return function_exists('mtag') || wp_script_is('marktag', 'enqueued');
}

if (is_marktag_active()) {
// Track event
}

3. Debug Mode

Add debug logging to verify events are firing:

function marktag_debug_event($event_type, $data) {
if (WP_DEBUG) {
error_log('MarkTag Event: ' . $event_type . ' - ' . json_encode($data));
}
}

Testing Your Implementation

1. Check Base Script Loading

  1. Visit your WordPress site

  2. Open browser Developer Tools (F12)

  3. Go to the Network tab

  4. Refresh page

  5. Look for the request to YOUR-MARKTAG-HOSTNAME/tag.js

  6. Should return 200 status

2. Verify Events

  1. Open browser Console tab

  2. Trigger an event (e.g., view a product)

  3. You should see network requests to your MarkTag hostname

  4. Or check markopolo dashboard for recent events

3. Test Event Data

Add temporary console logging:

<script>
// Wrap mtag to log events
var originalMtag = window.mtag;
window.mtag = function() {
console.log('MarkTag Event:', arguments);
return originalMtag.apply(this, arguments);
};
</script>

Common Issues & Troubleshooting

Events Not Firing

Check:

  • Base script loaded correctly (view page source)

  • No JavaScript errors in console

  • MarkTag hostname is correct

  • DNS verification completed

  • Events triggered at the right time (after the base script loads)

Solution:

  • Ensure the base script in <head>

  • The event code should run after the page load

  • Use wp_footer hook for most events

User Data Not Captured

Check:

  • User is logged in

  • User meta fields exist (billing_phone, etc.)

  • Data properly escaped in JavaScript

Solution:

// Add default values
$email = $current_user->user_email ?: '';
$phone = get_user_meta($current_user->ID, 'billing_phone', true) ?: '';

WooCommerce Events Not Tracking

Check:

  • WooCommerce is active

  • Using correct action hooks

  • Product data is available

  • The cart is not empty

Solution:

  • Test with simple products first

  • Verify hooks with add_action priority

  • Check if the theme overrides the default templates

Script Conflicts

Check:

  • Other tracking scripts are interfering

  • jQuery version conflicts

  • JavaScript minification issues

Solution:

// Ensure mtag loads after jQuery if needed
add_action('wp_enqueue_scripts', function() {
wp_enqueue_script('marktag', 'https://YOUR-HOSTNAME/tag.js', array('jquery'), null, true);
});

Best Practices

1. Use Child Theme

Always implement in a child theme to preserve changes during updates.

2. Sanitize Data

Always escape user data in JavaScript:

email: '<?php echo esc_js($user->user_email); ?>'

3. Handle Missing Data

Provide fallbacks for optional fields:

$phone = get_user_meta($user_id, 'billing_phone', true) ?: '';

4. Performance

  • Load MarkTag async

  • Minimize inline scripts

  • Combine events when possible

5. Privacy Compliance

  • Only track necessary data

  • Follow GDPR/privacy regulations

  • Inform users in the privacy policy

  • Provide opt-out mechanisms if required

Complete Implementation Checklist

  1. MarkTag base script installed in the header

  2. ViewContent event implemented on all pages

  3. ViewItem event set up on product pages (WooCommerce)

  4. AddToCart event triggered on cart actions

  5. ViewCart event is active on the cart page

  6. BeginCheckout event configured on checkout page

  7. Purchase event tracked on the thank you page

  8. Login event for user logins

  9. Signup event for new user registrations

  10. Lead/Contact events for form submissions

  11. Search events for on-site searches

  12. Custom events added as needed

  13. Testing completed successfully

  14. Events verified as visible in the Markopolo dashboard

  15. Documentation created for team reference

Getting Help

If you need assistance:

  1. Verify DNS Setup: Ensure server-side MarkTag is properly configured

  2. Review Browser Console: Look for JavaScript errors

  3. Test with Simple Events: Start with ViewContent before complex e-commerce events

  4. Contact Support: Provide site URL, implementation method, and specific issue

Remember: MarkTag events should start appearing in your Markopolo dashboard within minutes of proper implementation!

Did this answer your question?