Google Analytics

Update 2022
Nowadays you really should use Google Site Kit for implementing Google Analytics for your site and ignore the old method below.
Outdated method:

Most commonly used method of implementing Google Analytics to a site is by adding the global site tag, otherwise known as gtag.js.

Global site tag should be placed immediately after the <head> tag of every page, the wp_head action with a high priority is a good action to do that for WordPress:

Adding gtag.js to child theme’s functions.php
 * Google Analytics.
add_action('wp_head', function() {
  if(is_user_logged_in()) {
  <!-- Global site tag (gtag.js) - Google Analytics -->
  <script async src=""></script>
	window.dataLayer = window.dataLayer || [];
	function gtag(){dataLayer.push(arguments);}
	gtag('js', new Date());
	gtag('config', 'GA_MEASUREMENT_ID');
}, 5);

The 2 instances of GA_MEASUREMENT_ID should be replaced with your Google Analytics property ID that looks something like this: UA-123123-3.

The wp_head action is executed on every page (but not admin dashboard) so this one snippet ensures all your posts and pages are tracked.

The snippet includes a condition if(is_user_logged_in()) { return; } – this prevents logged in users from being tracked. In most cases this is just you, the site administrator. In case you have many users on the site and would like to track their pageviews, then this block can be removed.

If you’re looking to implement Universal Analytics (analytics.js) then it can be implemented in a similar manner, but you’re most likely looking at something outdated, because it’s over 7 years old and gtag.js has effectively replaced it.

Same goes for Google Tag Manager (gtm.js), the gtag.js is a newer solution that can probably get the job done.