New Google analytics API - how to send search, 404 info for tracking

457 Views Asked by At

Am working on a custom code to send the user search details and when ever 404 happens on the store. For that I have something like following

    <?php
        $page = '404';
        if ($page == '404') {
            $result[] = "ga('send', 'pageview', { 'page': '404/?url='+ document.location.href + document.location.search +'&ref=' + document.referrer,  'title': '404 Error'});";            
        }
        $searchText = 'abc';
        $searchResultCount = 0;// or number of records on search query
        if ($searchText != '') {
            if ($searchResultCount == 0) {
                $result[] = "ga('send', 'pageview', { 'page': $searchText,  'title': 'Search No rsult'});";   
            } else {
                $result[] = "ga('send', 'pageview', { 'page': $searchText,  'title':  $searchResultCount.' Found on Search'});";
            }
        }

        $moreTracking = implode("\n", $result);

 ?>

  <!-- BEGIN GOOGLE UNIVERSAL ANALYTICS CODE -->
    <script type="text/javascript">
        //<![CDATA[
        (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
            m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
        ga('create', 'UA-<?php echo $accountId; ?>-1', 'auto');
        ga('send', 'pageview');
        <?php echo $moreTracking; ?>

        //]]>
    </script>
    <!-- END GOOGLE UNIVERSAL ANALYTICS CODE -->

Am I adding it correctly? for to track 404 errors and search result or no search records found for user query.

1

There are 1 best solutions below

1
On

You are creating a UA code that ends with 1:

ga('create', 'UA-<?php echo $accountId; ?>-1', 'auto');

...GA account don't necessarily end with -1, they increment based on the number of web properties in teh account. So if a user has UA-232323-2 for example, it looks like the code will fail.

You also send the ga('send', 'pageview'); twice, once in the PHP and once in the JS tag, probably not intended. Its more likely you mean

ga('set', 'page', '/custom-page-name')

and then call the ga('send', 'pageview') after the PHP call:

 ga('create', 'UA-<?php echo $accountId; ?>', 'auto');
 <?php echo $moreTracking; ?>
 ga('send', 'pageview')

Also not sure if you are overcomplicating things - if the 404 page and/or search results are on distinct URLs, then you could just add the standard tracking script to those pages and see them appear in GA. But perhaps you want custom stuff to appear in the reports.

In all cases, you can use the Real Time report to check implementations are working as intended.