Skip to content

Instantly share code, notes, and snippets.

@mustafauysal
Created November 26, 2016 22:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mustafauysal/aa6e7ed1d84b9c148bea89527bc56190 to your computer and use it in GitHub Desktop.
Save mustafauysal/aa6e7ed1d84b9c148bea89527bc56190 to your computer and use it in GitHub Desktop.
Metrica single pageview
<?php
function yandex_metrica_pageview(){
if ( ! is_single() ) {
return false;
}
global $post;
$post_slug = '/' . $post->post_name . '/';
$metrica_options = get_option('metrica_options');
// check options
if ( ! is_array( $metrica_options ) || ! array_key_exists( 'counter_id', $metrica_options ) || ! array_key_exists( 'access_token', $metrica_options ) ) {
return false;
}
// transient cache for prevent too many request
$results = get_transient( 'ym_pageview_template_' . $metrica_options['counter_id'] );
$date1 = date( 'Ymd', strtotime( '-1 year' ) );
$date2 = date( 'Ymd' );
if ( ! $results ) {
$req_url = 'https://api-metrika.yandex.com/stat/v1/data.json?id='.$metrica_options['counter_id'].'&dimensions=ym:pv:URLPath&metrics=ym:pv:pageviews&filter=ym:pv:URLPathFull=='.$post_slug.'&oauth_token='.$metrica_options['access_token'].'&date1='.$date1.'&date2='.$date2;
$response = wp_remote_get( $req_url, array( 'timeout' => 7, 'httpversion' => '1.1', 'sslverify' => false ) );
$response_code = wp_remote_retrieve_response_code( $response );
if ( '200' == $response_code ) {
$body = json_decode( $response['body'] );
$dimensions = array();
foreach ( (array) $body->data as $item ) {
$dimensions[ $item->dimensions[0]->name ] = $item->metrics[0];
}
$pageviews = ( isset( $dimensions[ $post_slug ] ) ? $dimensions[ $post_slug ] : 0 );
set_transient( 'ym_pageview_template_' . $metrica_options['counter_id'], $pageviews, 600 );
return $pageviews;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment