1

I'm trying to find a solution to display the 5 post most viewed ( from google analytics) in my loop.

The only way I find at the moment is to use this plugin 'Google Analytics Top Content Widget '

However, I don't wan't to use that and I'll wish to be able to add in my loop because I have a really specific layout for that, than this plugin can not do .. .

ANy help will be amazing,

thank you guys !

  • IIRC, Google Analytics has an API. Have you tried it? – simonthesorcerer Jul 22 '15 at 17:44
1

If you have Yoast's Analytics plugin, this wouldn't be super hard. However, it will require some coding knowledge. I won't spell everything out for you, but I will point you in the right direction. Without Yoast, you'll have to review Lots of Documentation

  1. Load Yoast GA Files/Classes and Analytics ID from Yoast (or use Google Client API itself)
  2. Request Most Viewed Pages from Analytics and get post ids
  3. Get Posts and Loop

I've created an example here. Feel free to throw it in a function and try it as-is, though it is untested and may not work properly. This has a refresh-rate option (in minutes) and an option to hide your home page (which is usually the most viewed page, after all)

I stole a lot from the GA Top Content plugin.

function jr_get_ga_top_posts() {
    $expires = 5; // minutes
    $showhome = false; // if you want to hide the homepage, set true

    if ( false === ( $post_ids = get_transient('jr_ga_top_posts') ) ) {

        // check for Yoast and include files
        if ( ! class_exists( 'Yoast_Google_Analytics' ) ) {
            return;
        }

        if ( ! is_admin() ) {
            $path = dirname( GAWP_FILE );
            $files_to_include = array(
                'Yoast_Google_CacheParser'      => '/vendor/yoast/api-libs/google/io/Google_CacheParser.php',
                'Yoast_Google_Utils'            => '/vendor/yoast/api-libs/google/service/Google_Utils.php',
                'Yoast_Google_HttpRequest'      => '/vendor/yoast/api-libs/google/io/Google_HttpRequest.php',
                'Yoast_Google_IO'               => '/vendor/yoast/api-libs/google/io/Google_IO.php',
                'Yoast_Google_WPIO'             => '/vendor/yoast/api-libs/google/io/Google_WPIO.php',
                'Yoast_Google_Auth'             => '/vendor/yoast/api-libs/google/auth/Google_Auth.php',
                'Yoast_Google_OAuth2'           => '/vendor/yoast/api-libs/google/auth/Google_OAuth2.php',
                'Yoast_Google_Cache'            => '/vendor/yoast/api-libs/google/cache/Google_Cache.php',
                'Yoast_Google_WPCache'          => '/vendor/yoast/api-libs/google/cache/Google_WPCache.php',
                'Yoast_Google_Client'           => '/vendor/yoast/api-libs/google/Google_Client.php',
                'Yoast_Google_Analytics_Client' => '/vendor/yoast/api-libs/googleanalytics/class-google-analytics-client.php',
            );

            if ( version_compare( GAWP_VERSION, '5.4.3' ) >= 0 ) {
                unset( $files_to_include['Yoast_Google_Analytics_Client'] );
                $files_to_include['Yoast_Api_Google_Client'] = '/vendor/yoast/api-libs/class-api-google-client.php';
            }

            foreach ( $files_to_include as $class => $file ) {
                require_once $path . $file;
            }
        }

        $options = Yoast_GA_Options::instance()->options;
        $ga_id = isset( $options['analytics_profile'] ) ? $options['analytics_profile'] : '';

        // this might be the end
        if ( empty( $ga_id ) )
            return;

        $params = array(
            'ids'         => 'ga:'. $ga_id,
            'dimensions'  => 'ga:pageTitle,ga:pagePath',
            'metrics'     => 'ga:pageViews',
            'sort'        => '-ga:pageviews',
            'filters'     => urlencode( 'ga:pagePath=~' . $link_uri . '.*' ),
            'max-results' => 100,
        );

        $response = Yoast_Google_Analytics::get_instance()->do_request( add_query_arg( $params, 'https://www.googleapis.com/analytics/v3/data/ga' ) );

        $pages = isset( $response['response']['code'] ) && 200 == $response['response']['code']
            ? wp_remote_retrieve_body( $response )
            : array();

        $counter = 1;
        $maxpost = 5;
        $post_ids = array();

        foreach ( $pages as $page ) {
            // stop when reaching 5
            if ( $counter > $maxpost )
                break;

            $url = $page['path'];

            // Url is index and we don't want the homepage, skip
            if ( $url == '/' && ! $showhome ) {
                continue;
            }

            // We need to check if there are duplicates
            $default_permalink = strpos( $url, '?p=' );
            $query_var = strpos( $url, '?' );
            $and_var = strpos( $url, '&' );

            // Strip the query var off the url (if not using default permalinks)
            $url = ( false !== $query_var && false === $default_permalink )
                ? substr( $url, 0, $query_var )
                : $url;

            $and_var = strpos( $url, '&' );

            // strip extra args from ?p=id
            if ( $default_permalink && false !== $and_var ) {
                $url = substr( $url, 0, $and_var );
            }

            $post_id = url_to_postid( $url );

            if ( empty( $post_id ) || in_array( $post_id, $post_ids ) )
                continue;

            $post_ids[] = $post_id;
            $counter++;
        }

        set_transient('jr_ga_top_posts', $post_ids, $expires * MINUTE_IN_SECONDS );
    }

    // we can't go any further
    if ( empty( $post_ids ) )
        return;

    $query = new WP_Query( array(
        'post__in' => $post_ids,
    ) );

    return $query;
}

$top_posts = jr_get_ga_top_posts();

if ( ! empty( $top_posts ) {
    while( $top_posts->have_posts() ) : $top_posts->the_post();
        // loop...
    endwhile;
}
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.