Roots Discourse

Google Analytics via Soil: GA code not appearing anywhere

sage9

#1

Hello.

Here on discourse i did not find a recent topic about this, was wondering what is the suggested way of adding google analytics/tag code to the page so everything stays clean as it is?

Is there something soil related that solved this and I missed it?

Thanks for any help.

PS: tried add_theme_support('soil-google-analytics', 'UA-XXXX'); approach but nothing shows up anywhere


#2

Soil does this nicely:

add_theme_support('soil-google-analytics', 'UA-XXXXX-Y');

Add that at the end of this in app/setup.php:

Without Soil, use the wp_footer action (or wp_head if you want):

// app/setup.php
// The script is just a copy and paste of isogram: https://github.com/shinnn/isogram

add_action('wp_footer', function() { ?>
<script>
!function(G,o,O,g,l,e){G.GoogleAnalyticsObject=O;G[O]||(G[O]=function(){
(G[O].q=G[O].q||[]).push(arguments)});G[O].l=+new Date;l=o.createElement(g);
e=o.getElementsByTagName(g)[0];l.src='//www.google-analytics.com/analytics.js';
e.parentNode.insertBefore(l,e)}(window,document,'ga','script');

ga('create', 'UA-XXXXX-X', 'auto');
ga('send', 'pageview');
</script>
<?php });

Adding Google Analytics to Sage’s main.js or routes/common.js is not advisable.


#3

Hey, just found this, thanks!

add_theme_support('soil-google-analytics', 'UA-my-code-here');

but it doesnt add any GA code in my page locally: https://github.com/roots/soil/wiki/Google-Analytics It seems it only prints this on production, but where does it read WP_ENV from If I am not using Bedrock in my project? In wp-config it’s not working, I tried :slight_smile:

Also, this was updated in 2015, so is this still the way to go?


#4

Read more about the environment stuff here: https://github.com/roots/soil/wiki/Google-Analytics

Honestly, Soil is still a great way to go. The plugin looks like it was updated within the last month to make it GDPR ready, so it’s definitely still relevant.


#5

Great, will try to make it work, although I don’t see it printing any GA code anywhere even when setting WP_ENV :slight_smile:


#6

What if you add the filter mentioned in the link above?

add_filter('soil/loadGA', '__return_true');

#7

Did, unfortunately no change.


#8

By default, it will only load analytics.js when WP_ENV is set to production (or undefined) and the current user is not an administrator.

Are you signed in when you are viewing the site? What happens when viewing not signed in?

So far from my testing — plain WP install, no WP_ENV set, latest Sage, logged in and logged out — it is functioning how it should be.


#9

Nope, tried logged in/out etc., no changes. Can you screenshot your GA code and where it prints it? Seems weird …

Just to make sure, I’m adding this:

/**
 * Theme setup
 */
add_action('after_setup_theme', function () {
    /**
     * Enable features from Soil when plugin is activated
     * @link https://roots.io/plugins/soil/
     */
    add_theme_support('soil-clean-up');
    add_theme_support('soil-jquery-cdn');
    add_theme_support('soil-nav-walker');
    add_theme_support('soil-nice-search');
    add_theme_support('soil-relative-urls');

    add_theme_support('soil-google-analytics', 'UA-MY-CODE-HERE');

And inside filters.php added

add_filter('soil/loadGA', '__return_true');

which I don’t think should be necessary, but still.

By adding that you get the GA code printed in your html? Do you run some other commands first or do anything special when viewing the page?


#10

No other commands or anything special, this is just a new WP install.

Install procedure
wp valet new ga-not-loading --project=wp
cd ga-not-loading
valet link
cd wp-content/plugins
git clone git@github.com:roots/soil
wp plugin activate soil
cd ../themes
composer create-project roots/sage sage
cd sage
yarn && yarn build
wp theme activate sage/resources

Then added theme support for GA like I showed you above.

Here are two dumps from view-source:

Logged Out
<!doctype html>
<html lang="en-US">
  <head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>ga-not-loading &#8211; Just another WordPress site</title>
<link rel='dns-prefetch' href='//code.jquery.com' />
<link rel="stylesheet" href="/wp-content/themes/sage/dist/styles/main.css">
</head>
  <body class="home blog app-data index-data home-data front-page-data">
        <header class="banner">
  <div class="container">
    <a class="brand" href="http://ga-not-loading.test/">ga-not-loading</a>
    <nav class="nav-primary">
          </nav>
  </div>
</header>
    <div class="wrap container" role="document">
      <div class="content">
        <main class="main">
            <div class="page-header">
  <h1>Latest Posts</h1>
</div>

  
       <article class="post-1 post type-post status-publish format-standard hentry category-uncategorized">
  <header>
    <h2 class="entry-title"><a href="http://ga-not-loading.test/?p=1">Hello world!</a></h2>
    <time class="updated" datetime="2018-07-19T09:31:08+00:00">July 19, 2018</time>
<p class="byline author vcard">
  By <a href="http://ga-not-loading.test/?author=1" rel="author" class="fn">
    admin
  </a>
</p>
  </header>
  <div class="entry-summary">
    <p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p>
  </div>
</article>
  
  
        </main>
              </div>
    </div>
        <footer class="content-info">
  <div class="container">
      </div>
</footer>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>(window.jQuery && jQuery.noConflict()) || document.write('<script src="/wp-includes/js/jquery/jquery.js"><\/script>')</script>
<script src="/wp-content/themes/sage/dist/scripts/main.js"></script>
  <script>
          window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;
        ga('create','UA-XXXXX-Y','auto');
        ga('send','pageview')
  </script>
      <script src="https://www.google-analytics.com/analytics.js" async defer></script>
    </body>
</html>
Logged In
<!doctype html>
<html lang="en-US">
  <head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>ga-not-loading &#8211; Just another WordPress site</title>
<link rel='dns-prefetch' href='//code.jquery.com' />
<link rel="stylesheet" href="/wp-includes/css/dashicons.min.css?ver=4.9.7">
<link rel="stylesheet" href="/wp-includes/css/admin-bar.min.css?ver=4.9.7">
<link rel="stylesheet" href="/wp-content/themes/sage/dist/styles/main.css">
<style type="text/css" media="print">#wpadminbar { display:none; }</style>
<style type="text/css" media="screen">
	html { margin-top: 32px !important; }
	* html body { margin-top: 32px !important; }
	@media screen and ( max-width: 782px ) {
		html { margin-top: 46px !important; }
		* html body { margin-top: 46px !important; }
	}
</style>
</head>
  <body class="home blog logged-in admin-bar no-customize-support app-data index-data home-data front-page-data">
        <header class="banner">
  <div class="container">
    <a class="brand" href="http://ga-not-loading.test/">ga-not-loading</a>
    <nav class="nav-primary">
          </nav>
  </div>
</header>
    <div class="wrap container" role="document">
      <div class="content">
        <main class="main">
            <div class="page-header">
  <h1>Latest Posts</h1>
</div>

  
       <article class="post-1 post type-post status-publish format-standard hentry category-uncategorized">
  <header>
    <h2 class="entry-title"><a href="http://ga-not-loading.test/?p=1">Hello world!</a></h2>
    <time class="updated" datetime="2018-07-19T09:31:08+00:00">July 19, 2018</time>
<p class="byline author vcard">
  By <a href="http://ga-not-loading.test/?author=1" rel="author" class="fn">
    admin
  </a>
</p>
  </header>
  <div class="entry-summary">
    <p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p>
  </div>
</article>
  
  
        </main>
              </div>
    </div>
        <footer class="content-info">
  <div class="container">
      </div>
</footer>
    <script src="/wp-includes/js/admin-bar.min.js?ver=4.9.7"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>(window.jQuery && jQuery.noConflict()) || document.write('<script src="/wp-includes/js/jquery/jquery.js"><\/script>')</script>
<script src="/wp-content/themes/sage/dist/scripts/main.js"></script>
  <script>
          (function(s,o,i,l){s.ga=function(){s.ga.q.push(arguments);if(o['log'])o.log(i+l.call(arguments))}
      s.ga.q=[];s.ga.l=+new Date;}(window,console,'Google Analytics: ',[].slice))
        ga('create','UA-XXXXX-Y','auto');
        ga('send','pageview')
  </script>
  	<!--[if lte IE 8]>
		<script type="text/javascript">
			document.body.className = document.body.className.replace( /(^|\s)(no-)?customize-support(?=\s|$)/, '' ) + ' no-customize-support';
		</script>
	<![endif]-->
	<!--[if gte IE 9]><!-->
		<script type="text/javascript">
			(function() {
				var request, b = document.body, c = 'className', cs = 'customize-support', rcs = new RegExp('(^|\\s+)(no-)?'+cs+'(\\s+|$)');

						request = true;
		
				b[c] = b[c].replace( rcs, ' ' );
				// The customizer requires postMessage and CORS (if the site is cross domain)
				b[c] += ( window.postMessage && request ? ' ' : ' no-' ) + cs;
			}());
		</script>
	<!--<![endif]-->
			<div id="wpadminbar" class="nojq nojs">
							<a class="screen-reader-shortcut" href="#wp-toolbar" tabindex="1">Skip to toolbar</a>
						<div class="quicklinks" id="wp-toolbar" role="navigation" aria-label="Toolbar" tabindex="0">
				<ul id="wp-admin-bar-root-default" class="ab-top-menu">
		<li id="wp-admin-bar-wp-logo" class="menupop"><a class="ab-item" aria-haspopup="true" href="http://ga-not-loading.test/wp-admin/about.php"><span class="ab-icon"></span><span class="screen-reader-text">About WordPress</span></a><div class="ab-sub-wrapper"><ul id="wp-admin-bar-wp-logo-default" class="ab-submenu">
		<li id="wp-admin-bar-about"><a class="ab-item" href="http://ga-not-loading.test/wp-admin/about.php">About WordPress</a>		</li></ul><ul id="wp-admin-bar-wp-logo-external" class="ab-sub-secondary ab-submenu">
		<li id="wp-admin-bar-wporg"><a class="ab-item" href="https://wordpress.org/">WordPress.org</a>		</li>
		<li id="wp-admin-bar-documentation"><a class="ab-item" href="https://codex.wordpress.org/">Documentation</a>		</li>
		<li id="wp-admin-bar-support-forums"><a class="ab-item" href="https://wordpress.org/support/">Support Forums</a>		</li>
		<li id="wp-admin-bar-feedback"><a class="ab-item" href="https://wordpress.org/support/forum/requests-and-feedback">Feedback</a>		</li></ul></div>		</li>
		<li id="wp-admin-bar-site-name" class="menupop"><a class="ab-item" aria-haspopup="true" href="http://ga-not-loading.test/wp-admin/">ga-not-loading</a><div class="ab-sub-wrapper"><ul id="wp-admin-bar-site-name-default" class="ab-submenu">
		<li id="wp-admin-bar-dashboard"><a class="ab-item" href="http://ga-not-loading.test/wp-admin/">Dashboard</a>		</li></ul><ul id="wp-admin-bar-appearance" class="ab-submenu">
		<li id="wp-admin-bar-themes"><a class="ab-item" href="http://ga-not-loading.test/wp-admin/themes.php">Themes</a>		</li>
		<li id="wp-admin-bar-widgets"><a class="ab-item" href="http://ga-not-loading.test/wp-admin/widgets.php">Widgets</a>		</li>
		<li id="wp-admin-bar-menus"><a class="ab-item" href="http://ga-not-loading.test/wp-admin/nav-menus.php">Menus</a>		</li></ul></div>		</li>
		<li id="wp-admin-bar-customize" class="hide-if-no-customize"><a class="ab-item" href="http://ga-not-loading.test/wp-admin/customize.php?url=http%3A%2F%2Fga-not-loading.test%2F">Customize</a>		</li>
		<li id="wp-admin-bar-updates"><a class="ab-item" href="http://ga-not-loading.test/wp-admin/update-core.php" title="1 Plugin Update"><span class="ab-icon"></span><span class="ab-label">1</span><span class="screen-reader-text">1 Plugin Update</span></a>		</li>
		<li id="wp-admin-bar-comments"><a class="ab-item" href="http://ga-not-loading.test/wp-admin/edit-comments.php"><span class="ab-icon"></span><span class="ab-label awaiting-mod pending-count count-0" aria-hidden="true">0</span><span class="screen-reader-text">0 comments awaiting moderation</span></a>		</li>
		<li id="wp-admin-bar-new-content" class="menupop"><a class="ab-item" aria-haspopup="true" href="http://ga-not-loading.test/wp-admin/post-new.php"><span class="ab-icon"></span><span class="ab-label">New</span></a><div class="ab-sub-wrapper"><ul id="wp-admin-bar-new-content-default" class="ab-submenu">
		<li id="wp-admin-bar-new-post"><a class="ab-item" href="http://ga-not-loading.test/wp-admin/post-new.php">Post</a>		</li>
		<li id="wp-admin-bar-new-media"><a class="ab-item" href="http://ga-not-loading.test/wp-admin/media-new.php">Media</a>		</li>
		<li id="wp-admin-bar-new-page"><a class="ab-item" href="http://ga-not-loading.test/wp-admin/post-new.php?post_type=page">Page</a>		</li>
		<li id="wp-admin-bar-new-user"><a class="ab-item" href="http://ga-not-loading.test/wp-admin/user-new.php">User</a>		</li></ul></div>		</li></ul><ul id="wp-admin-bar-top-secondary" class="ab-top-secondary ab-top-menu">
		<li id="wp-admin-bar-search" class="admin-bar-search"><div class="ab-item ab-empty-item" tabindex="-1"><form action="http://ga-not-loading.test/" method="get" id="adminbarsearch"><input class="adminbar-input" name="s" id="adminbar-search" type="text" value="" maxlength="150" /><label for="adminbar-search" class="screen-reader-text">Search</label><input type="submit" class="adminbar-button" value="Search"/></form></div>		</li>
		<li id="wp-admin-bar-my-account" class="menupop with-avatar"><a class="ab-item" aria-haspopup="true" href="http://ga-not-loading.test/wp-admin/profile.php">Howdy, <span class="display-name">admin</span><img alt='' src='http://2.gravatar.com/avatar/589f19c795c09ac9ab5aff5ba59ef533?s=26&#038;d=mm&#038;r=g' srcset='http://2.gravatar.com/avatar/589f19c795c09ac9ab5aff5ba59ef533?s=52&#038;d=mm&#038;r=g 2x' class='avatar avatar-26 photo' height='26' width='26'></a><div class="ab-sub-wrapper"><ul id="wp-admin-bar-user-actions" class="ab-submenu">
		<li id="wp-admin-bar-user-info"><a class="ab-item" tabindex="-1" href="http://ga-not-loading.test/wp-admin/profile.php"><img alt='' src='http://2.gravatar.com/avatar/589f19c795c09ac9ab5aff5ba59ef533?s=64&#038;d=mm&#038;r=g' srcset='http://2.gravatar.com/avatar/589f19c795c09ac9ab5aff5ba59ef533?s=128&#038;d=mm&#038;r=g 2x' class='avatar avatar-64 photo' height='64' width='64'><span class='display-name'>admin</span></a>		</li>
		<li id="wp-admin-bar-edit-profile"><a class="ab-item" href="http://ga-not-loading.test/wp-admin/profile.php">Edit My Profile</a>		</li>
		<li id="wp-admin-bar-logout"><a class="ab-item" href="http://ga-not-loading.test/wp-login.php?action=logout&#038;_wpnonce=dea263b1d3">Log Out</a>		</li></ul></div>		</li></ul>			</div>
						<a class="screen-reader-shortcut" href="http://ga-not-loading.test/wp-login.php?action=logout&#038;_wpnonce=dea263b1d3">Log Out</a>
					</div>

		  </body>
</html>

#11

Ok, so I never installed Soil separately like you did here:

cd wp-content/plugins
git clone git@github.com:roots/soil
wp plugin activate soil

I thought this is somehow part of Sage already since the theme uses ‘soil-clean-up’ etc. by default. So all those add_theme_support calls are not doing anything without the plugin installed like this?

I guess that’s the step I’m missing, because I always only do:

composer create-project roots/sage

I never read anything about adding Soil plugin manually. Is there more I can read about this somewhere?


#12

From Github:

Soil is a commercial plugin available from roots.io/plugins/soil. It’s hosted on a public GitHub repository to allow for contributions from the community. It’s also published on Packagist to allow easier installation with Composer.

Sage has support for Soil out of the box — that’s why those add_theme_support calls are there. It’s similar to how themes will support WooCommerce or other plugins out of the box.


#13

Why doesn’t it work for me then? Or you mean it ‘has support’ but you still have to install the plugin manually?


#14

What is happening to you is totally expected. You have to install and activate the plugin first — everyone does.

When you install a plugin, it’s like: “yo I haz the features!”
And if the theme hasn’t declared support for said features, it’s like: “nah, I don’t support that.”
But if it has declared support, it’s like: “yay, I can do the features.”

When a theme says it has support for some features, it’s just saying that it is designed to work with whatever those features are.

I would recommend reading up on add_theme_support:
https://developer.wordpress.org/reference/functions/add_theme_support/


#15

Thanks mate,

of course, never before used Soil so was too convinced this is somehow a Sage feature and not a plugin that needs to be managed separately.

Working now as expected of course, have a great day! I sure will now :slight_smile:


Google Analytics