Skip to content
This repository has been archived by the owner on Jan 16, 2024. It is now read-only.

Commit

Permalink
Merge pull request #56 from roots/QWp6t-ga
Browse files Browse the repository at this point in the history
Add H5BP GA snippet
  • Loading branch information
retlehs committed Mar 13, 2015
2 parents 7082706 + 8ce330d commit 5800536
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,22 @@ Enable Soil's nice search (`/search/query/`) with:
add_theme_support('soil-nice-search');
```

### Google Analytics

Enable HTML5 Boilerplate's Google Analytics snippet

```php
add_theme_support('soil-google-analytics');
define('GOOGLE_ANALYTICS_ID', 'UA-XXXXXX');
```

By default, the GA snippet will only be shown for non-administrators. Administrators will get a dummy `ga()` function that writes its arguments to the console log for testing and development purposes. If you define `WP_ENV`, then non-production environments will always get dummy `ga()` function. You can override this via the `soil/displayGA` filter.

```php
add_filter('soil/displayGA', '__return_true'); // Appends H5BP's GA snippet
add_filter('soil/displayGA', '__return_false'); // Appends a dummy `ga()` function that writes arguments to console log
```

### JS to Footer

Move all scripts to `wp_footer` action hook with:
Expand Down
33 changes: 33 additions & 0 deletions modules/google-analytics.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace Roots\Soil\GoogleAnalytics;

/**
* Google Analytics snippet from HTML5 Boilerplate
*
* Cookie domain is 'auto' configured. See: http://goo.gl/VUCHKM
* You can enable/disable this feature in functions.php (or lib/config.php if you're using Sage):
* add_theme_support('soil-google-analytics');
* define('GOOGLE_ANALYTICS_ID', 'UA-XXXXXX');
*/
function google_analytics() {
if (!defined('GOOGLE_ANALYTICS_ID') || !GOOGLE_ANALYTICS_ID) {
return;
}
$displayGA = (!defined('WP_ENV') || WP_ENV === 'production') && !current_user_can('manage_options');
?>
<script>
<?php if (apply_filters('soil/displayGA', $displayGA)) : ?>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
<?php else : ?>
function ga() {if (window.console) {console.log('Google Analytics: ' + [].slice.call(arguments));}}
<?php endif; ?>
ga('create','<?= GOOGLE_ANALYTICS_ID; ?>','auto');ga('send','pageview');
</script>
<?php
}
add_action('wp_footer', __NAMESPACE__ . '\\google_analytics', 20);

0 comments on commit 5800536

Please sign in to comment.