How to use Google Analytics in WordPress site

GOAL

To understand the way to use Google Analytics and add google analytics tag into the header of the WordPress site.

Environment

WordPress 5.5.1
Theme: sparkling
Registered with Google Analytics

What is Google Analytics

Google Analytics is one of the services to analyze access log such as the number of access users, sessions, bounce rate and so on.

If you’ve not registered with Google Analytics yet, create an account and register.

Method

1. Get the tracking code

Login Google Analytics and open Admin menu.

Click “Tracking Code” and copy the Global Site Tag (gtag.js).

2. Paste the site tag to header.php of the theme

Open Appearance>Theme Editor in Dashboard.

Open hedaer.php and paste the copied code into the bottom of <head></head> tag.

<!--[if gt IE 9]><!-->
<html class="no-js" <?php language_attributes(); ?>> <!--<![endif]-->
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="<?php echo of_get_option( 'nav_bg_color' ); ?>">
<?php wp_head(); ?>

========================================
   put the tag from <script> to </script> here 
========================================

</head>

Save the change. Confirm that the tag is added in the source of your website.