Using Google Analytics data to show popular posts

Google Analytics Dashboard is an excellent plugin for showing site analytics on your WordPress dashboard.

However, it also has an open API built-in allowing anybody to access statistics from their own code. As a result I’ve created a new of small functions for my own site. To get these to work, ensure you have Google Analytics Dashboard installed, active and you’ve authenticated yourself using the OAuth method!

The most useful is the one I use in the sidebar to display the most popular posts. I was using specific plugins which track visits independently. However, I found these to inconsistent and unreliable.

This isn’t the version I use, as I’ve had to make specific modifications to only display posts and to tidy up the page titles. However, this is the same base code just with my very specific changes removed.

function latest_posts_list( $days, $showposts, $cache_hours ) {

   $cache_key = 'ga_posts_' . $days . $showposts;
  $output = get_transient( $cache_key );

  if ( !$output ) {

     $output = '';

    if ( $days == 0 ) {
       $start = '2006-09-01';
     } else {
         $start = date( 'Y-m-d', ( time() - ( 60 * 60 * 24 * $days ) ) );
    $end = date( 'Y-m-d' );
    $thispost = 1;

     $login = new GADWidgetData( get_option( 'gad_auth_token' ), get_option( 'gad_account_id' ) );
    $ga = new GALib( 'oauth', NULL, $login -> oauth_token, $login -> oauth_secret, $login -> account_id );
      $pages = $ga -> pages_for_date_period( $start, $end );

    foreach( $pages as $page ) {
       $url = $page[ 'value' ];
         $title = $page[ 'children' ][ 'value' ];
         $output .= '<li><a href="' . $url . '" rel="nofollow">' . $title . '</a&gtl';
        if ( current_user_can( 'edit_posts' ) ) { $output .= ' (' . $page[ 'children' ][ 'children' ][ 'ga:pageviews' ] . ' views)'; }
        $output .= '</li>';
        $thispost ++;
       if ( $thispost > $showposts ) break;
    set_transient( $cache_key, $output, 3600 * $cache_hours );
 echo $output;

Add this code to functions.php and then edit the line $start = '2006-09-01'; to reflect the date on which your blog statistics started. Then call latest_posts_list  with 3 parameters, all of which are required…

  1. The number of days across which to gather statistics. If you specify 0 then it will be for all time.
  2. The number of posts to display in the list.
  3. The number of hours to cache the results.

A sidebar example, with checks for function availability, would be…

<?php if ( function_exists( 'latest_posts_list' ) ) : ?>
        <h2>Recent Popular Posts</h2>
            <?php latest_posts_list( 30, 5, 24 ); ?>
<?php endif; ?>

This will display the 5 most popular posts within the last 30 days and will update this list every 24 hours.

Two further functions that I use elsewhere add live statistics data to a posts content. The code can also be added to your functions.php file…

function ga_visits_shortcode( $paras = '', $content = '' ) {

 extract( shortcode_atts( array( 'days' => '' ), $paras ) );
  if ( $days == '') { $days = 30; }
   $start_date = date( 'Y-m-d', ( time() - ( 60 * 60 * 24 * $days ) ) );
   $end_date = date( 'Y-m-d' );

 $login = new GADWidgetData( get_option( 'gad_auth_token' ), get_option('gad_account_id') );
   $ga = new GALib( 'oauth', NULL, $login -> oauth_token, $login -> oauth_secret, $login -> account_id );
   $visit_data = $ga -> total_visits_for_date_period( $start_date, $end_date );
 return number_format( $visit_data[ 'value' ] );
add_shortcode( 'ga_visits', 'ga_visits_shortcode' );

function ga_pageviews_shortcode( $paras = '', $content = '' ) {

 extract( shortcode_atts( array( 'days' =>'' ), $paras ) );
   if ( $days == '') { $days = 30; }
   $start_date = date( 'Y-m-d', ( time() - ( 60 * 60 * 24 * $days ) ) );
   $end_date = date( 'Y-m-d' );

 $login = new GADWidgetData( get_option( 'gad_auth_token' ), get_option( 'gad_account_id' ) );
 $ga = new GALib( 'oauth', NULL, $login -> oauth_token, $login -> oauth_secret, $login -> account_id );
   $visit_data = $ga -> total_pageviews_for_date_period( $start_date, $end_date );
 return number_format( $visit_data[ 'value' ] );
add_shortcode( 'ga_pageviews', 'ga_pageviews_shortcode' );

Now, all you have to do is call either shortcodes – [ga_visits] or [ga_pageviews] to output the number of visitors of pageviews that your site has had. Useful for promoting your site. There is one parameter, days, which allows you specify the time range this is for. If you don’t specify this parameter then 30 is assumed.

16 responses

  1. This looks awesome but I’m getting an error message trying to make the last two function items (shortcodes) work.
    Here’s the error I’m getting: Parse error: syntax error, unexpected ‘=’, expecting ‘)’

    This error is happening on this line of code within both of the last two functions: extract( shortcode_atts( array( ‘days’ = > ” ), $paras ) )
    I would love some assistance on this if you don’t mind.

    thank you in advance!

    1. Yes, sorry, my mistake – I tidied up the code before posting it and put a space where there shouldn’t have been one (between “=” and “>”). I’ve now corrected the code.

      1. Thank you very much for the super fast response!

        I modified the code and the short code content appeared on the page, but it’s “0”. Here’s the page I’m working on (…any ideas why the short cods provide a zeroed out result?

        Thanks again,

    2. I assume you have Google Analytics Dashboard installed and setup? You need to use the OAUTH method of authenticating it, though – if you didn’t, you’ll need to.

  2. You got it – that was the issue!
    Thank you so much. We’ll be throwing a donation your way soon, much appreciated!

    1. Happy to help Chais – I’ll update the post to clarify it for future 🙂

  3. Good afternoon, all done as described, but an error: “Warning: Invalid argument supplied for foreach () in”. How can I fix this? Thank you.

    1. That would suggest that is has returned no information for the date range. I found I got this if I specified a start date before my first post entry.

  4. K Armstrong avatar
    K Armstrong

    Thank you. This works well! One question. How do I remove the index page from the list of posts? I’ve increased the post display count to 10. The index page appears twice.

    1. The way I got around this was to add a line to only extract if the format of the URL was consistent with one of my posts (this also eliminated pages appearing in the results).

      It depends on your use of permalinks, but I added the following IF statement wrapper around the results…

      if ( substr( $url, 0, 3 ) == '/20' ) {

      1. K Armstrong avatar
        K Armstrong

        Thanks again! My PHP skills are not that great… Where would I place this code?

      2. Tried to cut and paste the code in, but it doesn’t like it 😉

        Okay, the IF statement line goes below the line…

        $url = $page[ 'value' ];

        You’ll then need to add a } after the line…

        $thispost ++;

  5. Great code. Thanks. Any chance of posting (or emailing) the modifications you’ve made? I’m not a programmer. I don’t know how to remove the blog and category names from the code so they don’t appear in the post results.
    Thank you!

    1. I have given details above on how to do this. The problem is that you have to extract what you need based on your own blog’s configuration – the details I’ve given will work on my site but won’t on many others. Google Analytics returns the URL and, assuming there’s an easy way of distinguishing post URLs from others then it can be done.

  6. […] Google Analytics Dashboard 提供的接口获得文章列表, 并输出到页面. 这里参考《Using Google Analytics data to show popular posts》提供的代码进行了一些修改, 可以编写方法如下. <?php /** * $days […]

  7. Hi,
    I am looking for such a solution in 2021. Does it still work for you today?

    Do you have an alternative to Google Analytics Dashboard because it has been removed from the marketplace?

    Thank you for the guide. Is amazing!

    Please reply.

Talk to me!

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: