add most viewed post by google analytic in loop [closed]

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 == "https://wordpress.stackexchange.com/" && ! $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;
}