Top Posts in WordPress Using Google Analytics

top posts with google analytics

We know we can display top posts in wordpress using wp postviews. Is it possible to display top posts using google analytics? Yes we can. Today let’s see how to display top posts in wordpress using google analytics.

Firstly register with google analytics and install the code snippet in your website. Then install the wordpress google analytics dashboard plugin. You can find the plugin here :

http://wordpress.org/extend/plugins/google-analytics-dashboard/ »

After it place the following code within the loop or in the sidebar.

<?php
	// options
	$showposts = 3; // how many posts/pages to display?
	$days = 30; // how many days back to calculate?

	// do not edit below this line
	$thispost = 1;
	$start = date('Y-m-d', (time() - (60 * 60 * 24 * $days)));
	$end = date('Y-m-d');
	$login = new GADWidgetData(get_option('gad_auth_token'), get_option('gad_account_id'));
	$ga = new GALib('client', $login->auth_token, '', '', $login->account_id);
	$pages = $ga->pages_for_date_period($start, $end);
	echo "<ul>";
	foreach($pages as $page) {
		$url = $page['value'];
		$title = $page['children']['value'];
		// ignore these page titles
		$ignore = array(
			'(not set)',
			'Page Title 1',
			'Page Title 2'
		);
		if(!in_array($title, $ignore)){
			// list any strings you would like to remove from the titles
			$remove = array(
				" | Company Name",
				" « Company Name"
			);
			$newtitle = str_replace($remove, "", $title);
			echo '<li><a href="' . $url . '" rel="nofollow">' . $newtitle . '</a></li>';
			$thispost++;
		}
		if($thispost > $showposts) break;
	}
	echo "</ul>";
?>
Hurray - we are up and running - post your comments -

Shortlink:

Posted by on December 28, 2011. Filed under Wordpress. You can follow any responses to this entry through the RSS 2.0. You can leave a response or trackback to this entry

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>