Adding Google Analytics to WordPress via code snippet

You can find the HTML code with your custom gTag ID in your Google Analytics account settings. You can copy that code into this snippet and place is in the functions.php file. It will enable GA to run on all pages except where the admin and editor are logged in.

/* Google Analytics */
function add_analytics() {
$GA_script = <<<'EOD'

<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=XXXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());;

  gtag('config', 'XXXXXX');
</script>
EOD;
if ( !current_user_can('edit_posts') ) echo $GA_script;
}
add_action('wp_head', 'add_analytics');