• 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)
  • How about using the wp_head action hook to add the script? The documentation has an example for pretty much this purpose at the bottom.

    Moderator bcworkz

    (@bcworkz)

    Hi kernix,
    “wp_enqueue_scripts” might be too early to output content. It’s not what the action is for anyway. What I’ve done is output the HTML from the “wp_print_scripts” action. I’m unsure how officially acceptable it is to do that, but it works for me.

    If the code from Google results in warnings, it’s probably nothing to be concerned about as long as you’re sure it was copied from Google correctly.

    When in doubt, find a plugin that does what you want to do and see how they do it ?? There are several plugins that help you set up Analytics which somehow inject gtag code.

    Thread Starter Jim

    (@kernix)

    bcworkz – thanks, I already looked at GA Analytics plugin by Jeff Starr assuming I’m remembering that correctly. It had waaaay too much code – I couldn’t figure it out. I’m weak on action and filter hooks so I haven’t even bothered trying to write even a simple plugin. Let me look into wp_print_scripts – I had no idea I was using enqueue scripts for something that it shouldn’t be used for…

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.