While you can add the snippet directly to header.php
, a better choice is probably the wp_head
action which should be triggered in any well-made, modern theme.
Using this hook allows you to insert the snippet without actually modifying your theme. It might look something like this:
function wpse_282929_conditionally_print_ga_snippet() {
if ( ! some_conditional_tag() ) {
return;
}
?>
{GA Snippet Here}
<?php
}
add_action( 'wp_head', 'wpse_282929_conditionally_print_ga_snippet' );
Where ! some_conditional_tag()
gets replaced by the appropriate conditional that would indicate you DO NOT WANT to print the snippet, and {GA Snippet Here}
obviously gets replaced with your specific GA snippet.
WordPress provides a number of conditional tags to determine what kind of page your visitor is currently on.
In fact, there are too many to list here, but you can find a complete listing on the Conditional Tags page in the codex.
As for where to include this code – if you are already working within a custom theme, you can just add it to your functions.php
file.
If not, I would probably recommend creating a must-use plugin. To do so, first create the mu-plugins
directory within wp-content
if it does not already exist. Next, create a file called ga-snippet.php
within the mu-plugins
directory and include your GA snippet function there.