How to properly add Google analytics to header.php
-
Theme sniffer gave me an error for the script tags added to the header file. I found a lot of articles about registering and enqueueing the script but none of them worked. What are you supposed to do with the <script> tags, the link to Google? I found the following code on stackexchange but I’m getting 2 errors:
if ( !is_user_logged_in() ) { function addAnalytics() { $analyticsTag = "<!-- Global site tag (gtag.js) - Google Analytics --> <script async src=" . '"' . "https://www.googletagmanager.com/gtag/js?id=G-MYCODEHERE" . '"' . "></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-MYCODEHERE'); </script> <!-- end Google Analytics -->"; echo $analyticsTag; } add_action( 'wp_enqueue_scripts', 'addAnalytics'); }
I’m getting an error for the script tag in quotes and for not escaping the variable. I’ll have to just go back to manually add the script to my header file and live the errors unless I can find a way to do it properly.
Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
- The topic ‘How to properly add Google analytics to header.php’ is closed to new replies.