How to Show Your Google Analytics Count in WordPress

by

Using a little php function inside your wordpress theme’s functions file, we can call up the total amount of visitors from a given month (ie: last 30 days).

Do you need a way to show your site users the amount of visitors you receive each month, which can utilise your Google Analytics account?

Then using this little PHP function below, we can easily print this information to the screen for anyone to read, Or if your feeling a little more savvy then… you can show this to registered or logged in users only or even just admin users…

1 – The Setup

In Order for this function to work, you will require a current copy of the Google Analytics API Class file which you can download here

Upload the analytics folder to your current themes root directory,
ie: wp-content/themes/your_theme_folder/analytics/

2 – The Function

Copy the function below into your themes ‘function.php‘ file… if you dont have one, create one!

// Google Analytic Account Number, Analytics Username & Password
function grab_analytic_count($account='ga:000000', $username='', $password='')
{
          session_start();
          $today = date('Y-m-d');
          $thirty_days_ago = date('Y-m-d', strtotime('-30 days'));
          require 'analytics/googleanalytics.class.php';
          try {
              $oAnalytics = new analytics($username,$password);
              $oAnalytics->useCache();
              $oAnalytics->setProfileById($account);
              $oAnalytics->setDateRange($thirty_days_ago, $today);
              $visitors = $oAnalytics->getVisitors();
              $total_visitors = array_sum($visitors);
              print number_format($total_visitors);
          } catch (Exception $e) {
              print 'Caught Exception: ' . $e->getMessage();
          }
}

3 – The PHP

Using this snippet of PHP you can place the call to the function anywhere you want within your template, simply enter your google analytics ‘ga:’ account number along with your username and password for your account.

the ‘ga:’ account should be at least 6 numbers in length, you can get this normaly in your Analytics code which you normaly paste into the footer of your website.. ie: ‘ga:123456‘.

<?php
if (function_exists('grab_analytic_count'))
echo grab_analytic_count('ga:123456','YOUR_GA_USERNAME','YOUR_GA_PASSWORD');
?>

4 – The Results

the output from the function will generate a Number based on your analytic results…
ie: 4,640

5 – What Next

This code can be used in your sidebar, or how about creating a widget just for displaying your count or adding extra code around the function call to check for various user levels and displaying it only to them.

6 – Create a Widget

To create a Widget within wordpress isnt as hard as you may think, first we add a little code to our functions.php file once again, this code will check to make sure wordpress can support widgets and that they are enabled, then we will register our own widget area with our unique name: Analytics or something along those lines…

if ( function_exists('register_sidebar') ) {
	register_sidebar(array(
		'name'=>'Analytics',
		'before_widget' => '<div>',
		'after_widget' => '</div>',
		'before_title' => '<h3>',
		'after_title' => '</h3>',
	));
}

With our Widget ready to go, we need to add code to our template were we want our widget to appear, this can be anywhere you want, in the footer, sidebar or header, in this case ill open up sidebar.php and paste in the following code.

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('analytics') ) : ?>
This is our Analytics Counter area, your widget is ready to use.
<?php endif; ?>

The code above will do this for us, keep in mind if you dont use your widget or it breaks for some reason its useful to have some holding text within the php code just for visual representation of where it will be placed..

7 – Create Widget Code

function wp_analytic_widget( $args = array() )
{
	// extract any paramerters we could make this our username, password & GA:Code
	extract($args);
	echo $before_widget;
	echo $before_title .' Analytics Counter '. $after_title;
        echo 'Total Monthly Visitors: ';
        echo grab_analytic_count('ga:123456','YOUR_USERNAME','YOUR_PASSWORD');
	echo $after_widget;
}
wp_register_sidebar_widget('Analytic Counter', 'wp_analytic_widget');

With all that code in place and uploaded, when you login to your admin area, under the appearance tab click on widgets you should be presented with something like this,

Analytics Widget

Now all you need to do, is drag that widget module over to your newley created widget area called ‘Analytics

When you visit your site you should be presented with your new widget area displaying your Google Count all wrapped in a div which you can style with CSS, by adding either an ID or class tag to the surounding div…

'before_widget' => '<div id="my_id_tag">',
'after_widget' => '</div>',

like i said above there is so much more opportunity to open this up to a lot more functionality, by wrapping the code in a if statement to check if the user is logged in? or shown only to admin users… or creating an entire plugin with lots of other features..

<?php
if( is_user_logged_in() ) { echo code; }
?>
<?php
if( is_admin() ) { echo code; }
?>

What do you think? as always comments and suggestions are welcome…

Tags: , , ,

Leave a Reply

Advertisement

Tracker by Hobo-Web