Interacting With the Google Analytics Core Reporting API

I needed a way for my clients to access analytics data that for a variety of reasons didn’t need or have full access to Google Analytics data through the traditional web app. I found a simple, yet soon to be deprecated, solution to my problem–the Google Analytics Core Reporting API.

There are a couple of libraries that an individual can use, depending on the language you’re working in, and since my expertise is in php, I chose to use the Google Analytics PHP Interface. This happens to interact with the older v2.4 API; unfortunately, I didn’t realize this until I already built the thing…moving on.

Start Me Up

OK, so let’s just assume you already have a Google Analytics account, because frankly why else would you need something like this? So, let’s define a few things, include the gapi class and fill in our information to connect to the core reporting API.

define('ga_email','your@email.com');     // GA Email
define('ga_password','elkkdafasff');     // 2-part authorization password
define('profile_id','2345678');          // Analytics profile ID

require_once 'gapi/gapi.class.php';
$ga = new gapi(ga_email,ga_password);

So now we’ve got an object to work with and we can start grabbing some data for our report.

With the core reporting api, you have certain metrics that you can look at depending on the dimension you’re interested in. To find exactly what metrics go with what dimensions, browse the Dimensions and Metrics Reference.

I already know that I’m interested in seeing the visits, pageviews, pages/visit, and bounce rate of all traffic sources (referrals, search engines, etc.). So, using the object we’ve already created I can define the dimensions and metrics I’m interested in, sort it by greatest number of visits, and limit my results to 50. You’ll also see that you can choose a date range. For this example I’m not providing one, so by default it will show the last month’s worth of data.

$dimensions  = array('source');
$metrics     = array('visits','pageviews','bounces');
$sort_metric = '-visits';

$ga->requestReportData(profile_id,
    $dimensions,
    $metrics,
    $sort_metric,
    $filter=null,
    $start_date=null,
    $end_date=null,
    $start_index=1,
    $max_results=50);

It is also possible to filter your data, so that if you wanted to see only referrals as a source, then you could replace $filter=null with $filter='medium==referral'. For a quick reference of what you might be able to filter, take a look at a list of common queries. Really just explore the documentation there in depth.

So we’ve got our data, now let’s put it in a format that we can browse:

<table>
  <thead>
    <tr>
      <th>&nbsp;</th>
      <th>Source</th>
      <th>Visits</th>
      <th>Pageviews</th>
      <th>Pages/Visit</th>
      <th>Bounce Rate</th>
    </tr>
  </thead>
  <tbody>
  <?php
  $i = 1;
  foreach($ga->getResults() as $result):
  ?>
    <tr>
      <td><?php echo $i; ?>.</td>
      <td><?php echo $result; ?></td>
      <td><?php echo number_format($result->getVisits()); ?></td>
      <td><?php echo number_format($result->getPageviews()); ?></td>
      <td><?php echo number_format(($result->getPageviews()/$result->getVisits()),2); ?></td>
      <td><?php echo number_format(($result->getBounces()/$result->getVisits())*100,2); ?>%</td>
    </tr>
  <?php
  $i++;
  endforeach
  ?>
  </tbody>
</table>

How easy was that?

Utilizing that as a foundation, I was able to turn it into a tool for clients, or for myself, making it easy to get a quick look at stats. If you’re at all interested in using it yourself, let me know in the comments.

Sponsored By
via Ad Packs

Why I Don’t Like Google (All That Much)

I had the opportunity over the past couple of days to experience the automated Google suspension hammer for one of their services. Without warning of any kind. Their system made a decision based on algorithms without any knowledge of the circumstances surrounding the situation, and continued to insist on its accuracy even after contacting a live person–until we could show concrete proof of our position.

Why is the onus on me to prove I’m doing something legitimate when their system makes a mistake, and why can they never own up to it? The best part, after resolving the problem, their email says they can’t guarantee the system won’t make the same mistake again. Huh?

Now they want me to complete a survey. Google is terrible at dealing with customers. Full stop.

I love certain Google products, so this isn’t to say the company is awful, but it’s pretty obvious how they feel about their customer base; they could not care less, as they’re mostly interested in advertising to us.

Rant over. Get back to work. Also, click that Google+ sharing button down there.

What Justice Means

Outcomes often seem unjust. The poor are in a constant state of suffering, while the privileged are continually extracting wealth from them. This state of affairs has the appearance of a zero-sum game–where one takes, the other gives–and those that have continue to accumulate at an accelerating pace. The poor have no chance at success in these conditions.

I have yet to read nearly enough to justify throwing the name Bastiat around.

The upper class discovered the keys to success long ago. They learned how to manipulate the system, to extract wealth from it, and to use it to enjoy many privileges for generations. The primary tool, of course, is the control of the state and her resources. This is done at the expense of the middle and lower classes. As in all things, however, the example the upper class sets will eventually be mimicked.

They, the masses of the people, imitating the upper classes, cry in their turn for privileges. They demand their right to employment, their right to credit, their right to education, their right to pensions. But at whose expense? — Bastiat

If the poor were to obtain these privileges, who would be left to pay? There are no lower classes to extract from or to ultimately confer the responsibility of payment. Because the upper and lower classes are constantly in a battle over control of the state’s coercive powers, wealth and power are unevenly and deleteriously distributed amongst the people. The wealthy use their vast influence over the state to sate the desires of the poor–at the expense of long term outcomes–in an effort to reduce their desire to gain influence.

We could always turn the tables on the well-off; the privileges the poor seek could be easily gained from them through taxation. But, and this goes for all classes,

If we wish to preserve a free society, it is essential that we recognize that the desirability of a particular object is not sufficient justification for the use of coercion.–F.A. Hayek

Wealth and resources are not obtained and distributed in zero-sum fashion. Value can be created, and in a level playing field, sans the coercive resources of the state, all classes of people can be free to obtain and create without issue. This is justice: freedom from coercion.

More Responsive Changes

When I was first building/designing my responsive site, I based my initial efforts on a slightly modified version of Joni Korpi’s Golden Grid System. It served me fairly well to begin with, but the way the media queries were set up made the layout’s reaction to changes in screen size never look quite right.

Needless to say I needed to make it work, and so I kept a lot of the underlying code intact, but pretty much abandoned the grid that was in use in that system, and came up with something that worked a little bit better for me. This allowed me to set a static width for larger screens and then adapt a little more naturally for smaller sizes.

Which is precisely the point in systems like that. You take what works for you, then adapt and modify the rest to better fit your needs.

The Stop Online Piracy/Protect IP Protests

Wow, that was an interesting day. It seems like nobody knew anything about this stuff, then suddenly, everyone became mildly aware. Wikipedia’s decision to go dark was a major catalyst for other folk’s decisions, and ultimately all of the hubbub got a partial result–the legislation is effectively dead.

But how did this even happen to begin with? Why is Congress so willing to do something as far reaching to something they have very little knowledge of? I’m going to guess it has a lot to do with the lobbying of the entertainment industry. No other group could benefit nearly as much from this kind of IP law.

Don’t get me wrong, I’m firmly on the side of IP holders–they deserve compensation for their hard work–but we’ve gone too far in our punishment of those that would infringe on these copyrights. Perhaps the punishment should be commensurate with the crime rather than far in excess of the damages?

For instance, the case of Jammie Thomas-Rasset, who at one point was ordered to pay $1.5 million for downloading 24 songs (24 songs!?), is a prime example of excessive punishment. In all honesty, were the artists damages really that high from this one individual? You can’t extract from this one person the damage that everyone has caused. The punishment is beyond excessive–it’s almost too difficult to believe. Fine the lady $5000 and be done with it–can an average individual be expected to pay $1.5 million when over one’s lifetime they’re only expected to earn between $1 million and $2 million? Unbelievable.

Copyright wasn’t meant to protect a creation for an eternity, virtually guaranteeing perpetual income for the creator and their grand children, nor was it designed to severely punish those that might copy. It was designed as a way to protect the creation of some thing for a short time in order to ensure that your creativity would be rewarded; this was seen as a way to encourage the creation of new work and nothing more. We’re approaching something more sinister, and one can hope that we will eventually develop saner copyright laws.

For now, stick to open source software where you can.

Code Snippets: Getting The Page Number in WordPress

I’m pretty sure I didn’t create this function, but it was one I used over two or three iterations of my site in order to display a page indicator in the style of “1 of 48.”

Pretty simple code:

function get_pagination(){
  // $paged - number of the current page - WordPress variable
  global $paged, $wp_query;
  // How many pages do we have?
  if ( !$max_page ) {
    $max_page = $wp_query->max_num_pages;
  }
  if(!$paged){
      $paged = 1;
  }
  if($max_page > 1){
     echo ''.$paged.' of '.$max_page.'';
  }
}

Not much else to say about it, but it has been useful from time to time.

Code Snippets: Ad Display Function For Use in A CMS Template

Since I was recently invited to be an AdPacks.com publisher, I had the pleasure of trying to find a way to integrate the ads tastefully into my site on the top level pages, as well as in individual posts. The current iteration of my site, as well as the last one, really only rely on the single column of content, so I lack a useful sidebar to place ads in; this pretty much limits me to placing ads in the content–well not quite in the content, but in the flow of content really.

So, I essentially needed ads to run after the first post, and only once on any page. In order to do that I needed a simple function that I could run in the WordPress loop, and guarantee my requirements were met.

Thus, the display_ads function was born:

function display_ads(){
    global $ad_count;
	if($ad_count < 1){
      $display = 'AD CODE HERE';
	  echo $display;
	}
	$ad_count++;
}

It's quick and dirty but pretty effective. Is there a better way to do this, because this is pretty much the quickest thing I could come up with on short notice? I am legitimately asking you, is there a better way?

Making Changes, Responsive Experimentation

With all of the changes going on in my industry, the improvement and exceedingly common use of responsive design techniques, and my general evolution as a web developer I needed to take a leap forward on my personal site. Hard to sit back and see all that was changing, see my own skill as a developer improve, and not do something. The problem has always been time.

I’ve been sitting on this redesign since at least November, and have scrapped many an iteration since then, but the holiday season kept me busy, and quite frankly I was never going to finish this unless I just launched the thing.

So in all it’s glory this is what it is for now. I’ll be making several changes as I go, improvements in the details, making sure I get everything right, because right now, it’s a hot mess, and adding back a lot of important functionality that I’ve not included in this theme just yet.

This site is tentatively responsive, but not everything plays nicely at this time. I’ll get there, I’m new to this. I’ve based the grid on Joni Korpi’s Golden Grid System, and it’s been modified slightly to accommodate my needs. A lot of my needs, unfortunately, made creating a workable grid kind of tough, but it works mostly.

I have a lot of modification to go through on older posts once I get to adding my archive links and search. I stupidly used a hacky grid in the old layout.

Well, take a look around, let me know what you think.

Upgrade to WordPress 3.3

I actually had not been following the latest WordPress developments too closely, and so I was quite pleasantly surprised by what the upgrade to WordPress 3.3 offered in terms of looks and functionality. But…

There were a few things that I had some issues with. First, I absolutely hate that the toolbar is on by default and apparently can’t be turned off without losing some important functionality. The toolbar is my least favorite feature of all the newer WordPress features. It’s ugly and intrusive. Why are you guys so focused on pushing this thing? Is it because of WordPress.com? I get it’s usefulness in that context, perhaps, but with the WordPress.org implementation it gets in my way more often than not.

I create custom plugins for all of my WordPress installations with some custom functionality and admin modifications appropriate to their contexts. Apparently a few of those were sloppily built because as soon as I upgraded, they promptly broke. There was just one line I screwed up in regards to calling a function within a class (typo), but it was something I didn’t notice as I never really ran those plugins through rigorous testing.

One of my favorite plugins for modifying the administration screen is Dean Robinson’s Fluency Admin. Unfortunately the update seems to not be compatible with it. Not one to be deterred, I went about modifying the new admin css to look at least passingly like Fluency.

If you were interested in doing the same, you could run this code through your functions.php file in a pinch, or better yet add it in a plugin:

function like_fluency_css() {
    echo '<style>
*,body {font-family: helvetica, sans-serif;}
        img#header-logo{display: none;}
        #adminmenu div.wp-menu-image {float: left;width: 1px;height: 28px;}
        #adminmenu .wp-menu-image a{display: none;}
        #wp-admin-bar-wp-logo{display: none;}
        #adminmenuback, #adminmenuwrap {background-color: #222;border-color: #444;border-right-color: #ddd;}
        #adminmenu li.wp-menu-separator {display: none;}
        #adminmenu div.separator {border-color: #0e6ac8;}
        #adminmenu a.menu-top, .folded #adminmenu li.menu-top, #adminmenu .wp-submenu .wp-submenu-head {border-top-color: #444;border-bottom-color: #000;}
        #adminmenu a {color:#fff;}
        #adminmenu .wp-submenu a {color:#777;}
        #adminmenu a:hover, #adminmenu li.menu-top>a:focus, #adminmenu ul.wp-submenu a:hover {color: #fff;}
        #adminmenu li.menu-top:hover>a, #adminmenu li.menu-top.focused>a, #adminmenu li.menu-top>a:focus {background-color: #000;text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.4);}
        #adminmenu li.wp-not-current-submenu:hover>a {border-top-color: #000;border-bottom-color: #000;}
        #adminmenu li.wp-not-current-submenu .wp-menu-arrow {border-top-color: #000;border-bottom-color: #000;background: #000;}
        #adminmenu li.wp-not-current-submenu .wp-menu-arrow div {background: #000;border-color: #000;}
        #collapse-menu {color: rgba(255,255,255,0.3);}
        #collapse-menu:hover {color: rgba(255,255,255,1.0);}
        #collapse-menu:hover #collapse-button {border-color: rgba(255,255,255,0.4);background-color: #333;background-image: -moz-linear-gradient(center bottom , #333, #444);}
        #collapse-button {border-color: rgba(255,255,255,0.2);background-color: #000;background-image: -moz-linear-gradient(center bottom , #111, #000);}
        #adminmenu .awaiting-mod, #adminmenu .update-plugins, #sidemenu a .update-plugins, #rightnow .reallynow {background-color: #464646;box-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);color: #FFFFFF;}
        .folded #adminmenu .wp-submenu-head {border-bottom-color: #ccc;border-top-color: #ccc;}
        .folded #adminmenu li.wp-has-current-submenu, .folded #adminmenu li.current.menu-top {border-bottom-color: #6D6D6D;border-top-color: #808080;}
    </style>';
}
add_action('admin_head', 'like_fluency_css'); //remove logo from admin

There will be more in the days to come, but for now, I’m happy with the progress the team continues to make, and thanks for a great, free product!

I’ve Become an AdPacks.com Publisher

I hadn’t given much consideration to including any sort of advertising on my blog in the past, but was given the opportunity to become a publisher in an advertising network recently, and I’m pretty honored by that. “What? My content might be fit for advertising?” Alright, I’m flattered. Feel like I’ve joined an exclusive club.

So, you may start noticing all of the ads here for services geared towards you, the web developer, all being served through AdPacks.com. Lucky for you, these are the only ads you’re going to see.

A little about AdPacks.com from their website:

Ad Packs is a division of BuySellAds.com, a well respected and hard-working bunch of design and advertising enthusiasts. BSA has been in business for almost 3 years and they serve ads on over 2,900 websites amounting to ~3 billion impressions per month. You can learn more about BSA from their about page or by checking out the BSA rap song on YouTube.

Never really considered mine to be the sort of site that might be useful for someone to advertise on. Maybe it is, maybe it still isn’t. Hopefully I can connect some folks with some fine, fine services, and by all means, click on through if you’re interested.