添加Google Analytic in Loop中浏览量最高的帖子

时间:2015-07-22 作者:tibewww

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 !

1 个回复
SO网友:johnrom

如果你有Yoast的分析插件,这不会很难。然而,它需要一些编码知识。我不会为你详细说明一切,但我会为你指出正确的方向。如果没有Yoast,你必须复习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

    我从GA顶级内容插件中偷了很多东西。

    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;
    }
    

结束

相关推荐

WP_QUERY LOOP ELSE语句未执行

我有两个WP_query 在我的frontpage中循环。php文件:<div id=\"aanbod\"> <div class=\"container-fluid section-name-cont\"> <div class=\"container\"> <div class=\"row\"> <div class=\"col-xs-12 section-name\"