Adding Custom Analytics and Tracking

This guide shows you how to add custom analytics and tracking codes to your DigiFusion child theme, including Google Analytics, Facebook Pixel, and custom tracking events.

Adding Google Analytics 4

Add the following function to your child theme’s functions.php file:

function digifusion_child_add_google_analytics() {
    $ga_id = 'G-XXXXXXXXXX'; // Replace with your GA4 Measurement ID
    
    if ( empty( $ga_id ) ) {
        return;
    }
    ?>
    <!-- Google tag (gtag.js) -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo esc_attr( $ga_id ); ?>"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', '<?php echo esc_attr( $ga_id ); ?>');
    </script>
    <?php
}
add_action( 'wp_head', 'digifusion_child_add_google_analytics' );

Adding Facebook Pixel

Add this function to track Facebook Pixel events:

function digifusion_child_add_facebook_pixel() {
    $pixel_id = '1234567890123456'; // Replace with your Pixel ID
    
    if ( empty( $pixel_id ) ) {
        return;
    }
    ?>
    <!-- Facebook 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', '<?php echo esc_attr( $pixel_id ); ?>');
        fbq('track', 'PageView');
    </script>
    <noscript>
        <img height="1" width="1" style="display:none" 
             src="https://www.facebook.com/tr?id=<?php echo esc_attr( $pixel_id ); ?>&ev=PageView&noscript=1"/>
    </noscript>
    <?php
}
add_action( 'wp_head', 'digifusion_child_add_facebook_pixel' );

Adding Google Tag Manager

For Google Tag Manager implementation:

function digifusion_child_add_gtm_head() {
    $gtm_id = 'GTM-XXXXXXX'; // Replace with your GTM Container ID
    
    if ( empty( $gtm_id ) ) {
        return;
    }
    ?>
    <!-- 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','<?php echo esc_attr( $gtm_id ); ?>');</script>
    <!-- End Google Tag Manager -->
    <?php
}
add_action( 'wp_head', 'digifusion_child_add_gtm_head' );

function digifusion_child_add_gtm_body() {
    $gtm_id = 'GTM-XXXXXXX'; // Replace with your GTM Container ID
    
    if ( empty( $gtm_id ) ) {
        return;
    }
    ?>
    <!-- Google Tag Manager (noscript) -->
    <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=<?php echo esc_attr( $gtm_id ); ?>"
    height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
    <!-- End Google Tag Manager (noscript) -->
    <?php
}
add_action( 'wp_body_open', 'digifusion_child_add_gtm_body' );

Custom Event Tracking

Create a JavaScript file assets/js/custom-tracking.js in your child theme:

// Custom event tracking
document.addEventListener('DOMContentLoaded', function() {
    
    // Track button clicks
    const trackButtons = document.querySelectorAll('.digi-button, .wp-block-button__link');
    trackButtons.forEach(function(button) {
        button.addEventListener('click', function() {
            const buttonText = this.textContent.trim();
            
            // Google Analytics 4
            if (typeof gtag !== 'undefined') {
                gtag('event', 'button_click', {
                    'button_text': buttonText,
                    'page_title': document.title
                });
            }
            
            // Facebook Pixel
            if (typeof fbq !== 'undefined') {
                fbq('track', 'ButtonClick', {
                    button_text: buttonText
                });
            }
        });
    });
    
    // Track form submissions
    const forms = document.querySelectorAll('form');
    forms.forEach(function(form) {
        form.addEventListener('submit', function() {
            const formId = this.id || 'unknown_form';
            
            // Google Analytics 4
            if (typeof gtag !== 'undefined') {
                gtag('event', 'form_submit', {
                    'form_id': formId
                });
            }
            
            // Facebook Pixel
            if (typeof fbq !== 'undefined') {
                fbq('track', 'Contact');
            }
        });
    });
    
    // Track scroll depth
    let scrollDepth = 0;
    window.addEventListener('scroll', function() {
        const currentScroll = Math.round((window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100);
        
        if (currentScroll > scrollDepth && currentScroll % 25 === 0) {
            scrollDepth = currentScroll;
            
            // Google Analytics 4
            if (typeof gtag !== 'undefined') {
                gtag('event', 'scroll_depth', {
                    'scroll_percentage': scrollDepth
                });
            }
        }
    });
});

Enqueue the tracking script by adding this to your functions.php:

function digifusion_child_enqueue_tracking_scripts() {
    wp_enqueue_script(
        'digifusion-child-tracking',
        get_stylesheet_directory_uri() . '/assets/js/custom-tracking.js',
        array(),
        wp_get_theme()->get('Version'),
        true
    );
}
add_action( 'wp_enqueue_scripts', 'digifusion_child_enqueue_tracking_scripts' );

Conditional Tracking

Add tracking only on specific pages or post types:

function digifusion_child_conditional_tracking() {
    // Only add tracking on blog posts
    if ( is_single() && get_post_type() === 'post' ) {
        $ga_id = 'G-XXXXXXXXXX';
        ?>
        <script>
            gtag('event', 'blog_post_view', {
                'post_title': '<?php echo esc_js( get_the_title() ); ?>',
                'post_category': '<?php echo esc_js( get_the_category_list( ', ' ) ); ?>'
            });
        </script>
        <?php
    }
    
    // Add e-commerce tracking for WooCommerce
    if ( class_exists( 'WooCommerce' ) && is_woocommerce() ) {
        // WooCommerce specific tracking
        if ( is_product() ) {
            global $product;
            ?>
            <script>
                gtag('event', 'view_item', {
                    'currency': '<?php echo esc_js( get_woocommerce_currency() ); ?>',
                    'value': <?php echo esc_js( $product->get_price() ); ?>,
                    'item_id': '<?php echo esc_js( $product->get_id() ); ?>',
                    'item_name': '<?php echo esc_js( $product->get_name() ); ?>'
                });
            </script>
            <?php
        }
    }
}
add_action( 'wp_footer', 'digifusion_child_conditional_tracking' );

GDPR Compliance Setup

Add consent management for GDPR compliance:

function digifusion_child_add_consent_banner() {
    if ( ! isset( $_COOKIE['analytics_consent'] ) ) {
        ?>
        <div id="consent-banner" style="position: fixed; bottom: 0; left: 0; right: 0; background: #333; color: white; padding: 15px; z-index: 9999;">
            <p>We use cookies and tracking to improve your experience. 
            <button id="accept-tracking" style="background: #007cba; color: white; border: none; padding: 5px 15px; margin-left: 10px;">Accept</button>
            <button id="decline-tracking" style="background: #666; color: white; border: none; padding: 5px 15px; margin-left: 5px;">Decline</button></p>
        </div>
        <script>
            document.getElementById('accept-tracking').addEventListener('click', function() {
                document.cookie = 'analytics_consent=accepted; path=/; max-age=31536000';
                document.getElementById('consent-banner').style.display = 'none';
                // Initialize tracking here
                if (typeof gtag !== 'undefined') {
                    gtag('consent', 'update', {
                        'analytics_storage': 'granted'
                    });
                }
            });
            
            document.getElementById('decline-tracking').addEventListener('click', function() {
                document.cookie = 'analytics_consent=declined; path=/; max-age=31536000';
                document.getElementById('consent-banner').style.display = 'none';
            });
        </script>
        <?php
    }
}
add_action( 'wp_footer', 'digifusion_child_add_consent_banner' );

Replace all placeholder IDs (like G-XXXXXXXXXX, GTM-XXXXXXX) with your actual tracking IDs before implementing these solutions.