Adding Google Analytics and AdSense to MediaWiki

From GlassTTY
Jump to: navigation, search

Google Analytics

Add the following to the bottom of the LocalSettings.php file, replacing TRACKNGID with an appropriate Google tracking ID.

   $wgHooks['BeforePageDisplay'][] = function( OutputPage &$out, Skin &$skin ) {
       $code = <<<HTML
       <script async src="https://www.googletagmanager.com/gtag/js?id=TRACKING_ID"></script>
       <script>
         window.dataLayer = window.dataLayer || [];
         function gtag(){dataLayer.push(arguments);}
         gtag('js', new Date());
   
         gtag('config', 'TRACKINGID');
       </script>
       HTML;
   
        $out->addHeadItem( 'gtag-insert', $code );
        return true;
   };

Google AdSense

Add the appropriate AdSense code to the bottom of the LocalSettings.php file e.g.

   $wgHooks['SkinAfterContent'][] = function(&$siteNotice, $skin) {
           $siteNotice .= <<< EOT

 

       <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
       
       <script>
           (adsbygoogle = window.adsbygoogle || []).push({});
       </script>

 

       EOT;
       return true;
   };