Skip to content

Instantly share code, notes, and snippets.

@tollmanz
Created October 13, 2012 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tollmanz/3882534 to your computer and use it in GitHub Desktop.
Save tollmanz/3882534 to your computer and use it in GitHub Desktop.
Get Google Analytics Data With Incrementor
<?php
function zt_get_top_posts( $args, $force = false ) {
// Define the cache key
$identifier = md5( maybe_serialize( $args ) );
$cache_key = 'top-posts-' . $identifier;
// Define the cache group
$cache_group = 'zt-ga-data-' . zt_get_incrementor();
// Attempt to get data from cache
$top_posts = wp_cache_get( $cache_key, $cache_group );
// If not found in cache or forced, regenerate
if ( false === $top_posts || true === $force ) {
// Get posts from GA
$top_posts = zt_generate_top_posts( $args );
// If none were found, save a dummy value so the caller knows that
if ( false === $top_posts )
$top_posts = 'none-found';
// Set the result to the cache
wp_cache_set( $cache_key, $top_posts, $cache_group, 3600 );
}
return $top_posts;
}
function zt_get_incrementor( $refresh = false ) {
$incrementor_key = 'google-analytics';
$incrementor_group = 'zt-incrementors';
$incrementor_value = wp_cache_get( $incrementor_key, $incrementor_group );
if ( false === $incrementor_value || true === $refresh ) {
$incrementor_value = time();
wp_cache_set( $incrementor_key, $incrementor_value, $incrementor_group );
}
return $incrementor_value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment