Page 1 of 1

Retrieve Google and AWIS Alexa Page Rank for WordPress

Retrieve Google and AWIS Alexa Page Rank for WordPress
   2

For whatever reason you can think of, for the fun of it, or to show off how well your website is doing; displaying the Google pagerank and/or the Alexa ranking of your website is kind-a nice to have. This article is an updated version of a previous article I wrote, but since the Alexa link no longer works, the official (free up to 1,000 queries a month) Amazon AWIS API needs to be used and we won’t be exceeding the 1,000 free queries per month with this method.

I have seen several useful PHP scripts that can help with that, but they all kind-a rely on the fact that a page is being loaded, and while loading the Google Rank and Alexa Rank are begin retrieved, over an over again. This is not only causing an unneeded load on the Google and Alexa servers, but it’s also slowing down the loading of your website (even though it might not be noticeable by the end-user).

Both Google Rank and Alexa do not refresh multiple times per day, so a once a day refresh would be good enough.
In this article I’ll show you how I have implemented this in WordPress.

P.s. for those who’d like to see this as a video training, Webucator was kind enough to make this article available as a video as well, you can find it at the end of this article.




This article is outdated …

OUTDATED – Google Rank and Alexa Ranking no longer in service 

Both Google and Amazon (Alexa) have taken their beloved ranking services down.
This makes this article obsolete.

I’m leaving the article for reference though, since the code may be helpful for implementing other services.

Goal – Retrieving Google and Alexa Rank once a day

The goal of this article is to end up with a WordPress setup that retrieves both Google Rank and Alexa Rank once a day, and store the rankings in the WordPress database for use during the day, versus retrieving both each time a page is being loaded.

I’ll explain how we get each rank, and how we store, retrieve and update the rankings in WordPress.

Required experience and access … 

To implement the suggested code, some PHP experience is required.
You will also need to be able to upload files to your WordPress website, and be able to edit one or two files on your WordPress website. Keep in mind that this is NOT a PLUGIN!

I recommend reading the full article first, before bluntly pasting the code into your WordPress website.

Updated version: Use Alexa Web Information Services API 

This article is an updated version of the “Retrieve Google and Alexa Page Rank for WordPress” article.
The link used at the time to retrieve Alexa data is no longer working properly it seems, so in this method we utilize the AWIS API.

 

How to retrieve Alexa Ranking with Amazon AWIS API?

Unfortunately, the old method with a link like this, no longer seems to work properly:


http://data.alexa.com/data?cli=10&url=www.tweaking4all.com

To retrieve the link, we now need to use the official Amazon AWIS API.
This means that you have to sign up. The first 1,000/month are free, so with the method I propose here, you should be just fine even if you fire this function every hour (31 days × 24 hours = 744 queries in a month).

So first head over to Amazon for Alexa WebServices (you’ll need the Alexa Web Information Services) through this link: https://aws.amazon.com/alexa/

Once you’ve signed up, you will have two keys available in your account – an accessKeyId and a secretAccessKey. We need those later on!

From their FAQ:

To use AWIS, you first need to sign up for the Alexa Web Information service.

Visit the service detail page and click on the “Sign up for AWIS” button.

After completing the registration process click on “Go to the Management Console” button.

On the AWS Management Console page select the drop down arrow next to your name in the top right hand corner, and select “Security Credentials“.
(Note: AWIS is not listed on the AWS Management Console page.)

Select “Access Keys (Access Key ID and Secret Access Key)” and “Create New Access Keys” to get the access keys that you will use to make requests to the service.

Once we have these two keys, we can use the following code to retrieve the Alexa Global Ranking score through the AWIS API.

First we need a separate file, which I called “awis_urlinfo.php“, with the following content (I modified an example that I found at Amazon – this code has been updated 8/13/2017 so it uses https instead of just http):


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
/**
 * Makes a request to AWIS for site info.
 */

class UrlInfo {

    protected static $ActionName        = 'UrlInfo';
    protected static $ResponseGroupName = 'Rank';
    protected static $ServiceHost      = 'awis.amazonaws.com';
    protected static $NumReturn         = 10;
    protected static $StartNum          = 1;
    protected static $SigVersion        = '2';
    protected static $HashAlgorithm     = 'HmacSHA256';

    public function UrlInfo($accessKeyId, $secretAccessKey, $site) {
        $this->accessKeyId = $accessKeyId;
        $this->secretAccessKey = $secretAccessKey;
        $this->site = $site;
    }

    /**
     * Get site info from AWIS.
     */

    public function getUrlInfo() {
        $queryParams = $this->buildQueryParams();
        $sig = $this->generateSignature($queryParams);
        $url = 'https://' . self::$ServiceHost . '/?' . $queryParams . '&Signature=' . $sig;
        $ret = self::makeRequest($url);
        return self::parseResponse($ret);
    }

    /**
     * Builds current ISO8601 timestamp.
     */

    protected static function getTimestamp() {
        return gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time());
    }

    /**
     * Builds query parameters for the request to AWIS.
     * Parameter names will be in alphabetical order and
     * parameter values will be urlencoded per RFC 3986.
     * @return String query parameters for the request
     */

    protected function buildQueryParams() {
        $params = array(
            'Action'            => self::$ActionName,
            'ResponseGroup'     => self::$ResponseGroupName,
            'AWSAccessKeyId'    => $this->accessKeyId,
            'Timestamp'         => self::getTimestamp(),
            'Count'             => self::$NumReturn,
            'Start'             => self::$StartNum,
            'SignatureVersion'  => self::$SigVersion,
            'SignatureMethod'   => self::$HashAlgorithm,
            'Url'               => $this->site
        );
        ksort($params);
        $keyvalue = array();
        foreach($params as $k => $v) {
            $keyvalue[] = $k . '=' . rawurlencode($v);
        }
        return implode('&',$keyvalue);
    }

    /**
     * Makes request to AWIS
     * @param String $url   URL to make request to
     * @return String       Result of request
     */

    protected static function makeRequest($url) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 4);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /**
     * Parses XML response from AWIS and displays selected data
     * @param String $response    xml response from AWIS
     */

    public static function parseResponse($response) {
        $xml = new SimpleXMLElement($response,null,false, 'http://awis.amazonaws.com/doc/2005-07-11');
        if($xml->count() && $xml->Response->UrlInfoResult->Alexa->count()) {
            return $xml->Response->UrlInfoResult->Alexa->TrafficData->Rank.'<br>';
        } else { return '0'; }
    }

    /**
     * Generates an HMAC signature per RFC 2104.
     *
     * @param String $url       URL to use in createing signature
     */

    protected function generateSignature($url) {
        $sign = "GET\n" . strtolower(self::$ServiceHost) . "\n/\n". $url;
        $sig = base64_encode(hash_hmac('sha256', $sign, $this->secretAccessKey, true));
        return rawurlencode($sig);
    }
}
?>

Now to retrieve our score we in essence only need to create the object and pass our keys, something like this:


    $urlInfo = new UrlInfo("ABGV$VSNDGFJMSNBBAAB", "A03bahPpcTcHA8+xbK+1x81JllhxC30BCXb+AA0bx", "www.tweaking4all.com");
    echo "AlexaRank for $url: ". $urlInfo->getUrlInfo();

The first parameter is our accessKeyId and the second parameter is our secretAccessKey. The last parameter, of course, is the URL we’d like to see the score from.
Note that you should keep your keys in a safe place so nobody can access them and abuse them for their own purposes.

Note that the key and secret key in this example are made up, so they will not work – you will have to get your own!

 

How to retrieve Google Page Rank?

Retrieving the Google PageRank is a little bit more complicated, as there is no API offered by Google to fetch that, so we need a trick for that one.

 I’ll admit right away that I did not write the now following class myself, but rather, found some well working code at 99WebTools.com, but there are plenty other websites that offer this code as well, so I’m not sure who the original developer was that actually wrote this.

First we need to create a file with the name “prclass.php“, with the following text content (this is a somewhat cleaned up version of the code that I found at 99WebTools):


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
class GooglePR {
 public function get_google_pagerank($url) {
  $query="http://toolbarqueries.google.com/tbr?client=navclient-auto&ch=".$this->CheckHash($this->HashURL($url)). "&features=Rank&q=info:".$url."&num=100&filter=0";
  $data=file_get_contents($query);
  $pos = strpos($data, "Rank_");
  if($pos === false) {} else {
   $pagerank = substr($data, $pos + 9);
   return $pagerank;
  }
 }
 public function StrToNum($Str, $Check, $Magic) {
  $Int32Unit = 4294967296; // 2^32
  $length = strlen($Str);
  for ($i = 0; $i < $length; $i++) {
   $Check *= $Magic;
   if ($Check >= $Int32Unit) {
    $Check = ($Check - $Int32Unit * (int) ($Check / $Int32Unit));
    $Check = ($Check < -2147483648) ? ($Check + $Int32Unit) : $Check;
   }
   $Check += ord($Str{$i});
  }
  return $Check;
 }
 public function HashURL($String) {
  $Check1 = $this->StrToNum($String, 0x1505, 0x21);
  $Check2 = $this->StrToNum($String, 0, 0x1003F);
  $Check1 >>= 2;
  $Check1 = (($Check1 >> 4) & 0x3FFFFC0 ) | ($Check1 & 0x3F);
  $Check1 = (($Check1 >> 4) & 0x3FFC00 ) | ($Check1 & 0x3FF);
  $Check1 = (($Check1 >> 4) & 0x3C000 ) | ($Check1 & 0x3FFF);
  $T1 = (((($Check1 & 0x3C0) << 4) | ($Check1 & 0x3C)) <<2 ) | ($Check2 & 0xF0F );
  $T2 = (((($Check1 & 0xFFFFC000) << 4) | ($Check1 & 0x3C00)) << 0xA) | ($Check2 & 0xF0F0000 );
  return ($T1 | $T2);
 }
 public function CheckHash($Hashnum) {
  $CheckByte = 0;
  $Flag = 0;
  $HashStr = sprintf('%u', $Hashnum) ;
  $length = strlen($HashStr);
   
  for ($i = $length - 1; $i >= 0; $i --) {
   $Re = $HashStr{$i};
   
   if (1 === ($Flag % 2)) {
    $Re += $Re;
    $Re = (int)($Re / 10) + ($Re % 10);
   }
   
   $CheckByte += $Re;
   $Flag ++;
  }
   
  $CheckByte %= 10;
   
  if (0 !== $CheckByte) {
   $CheckByte = 10 - $CheckByte;
   
   if (1 === ($Flag % 2) ) {
    if (1 === ($CheckByte % 2)) {
     $CheckByte += 9;
    }
    $CheckByte >>= 1;
   }
  }
   
  return '7'.$CheckByte.$HashStr;
 }
}
?>

I’ll save you the headache on how this exactly works, but it all comes down to a mathematical calculation which is needed to add a Jenkins Hash for the link to work.

The following code is an example on how to use this class:


1
2
3
4
5
6
<?
    require("prclass.php");
    $url='//www.tweaking4all.com/';
    $pr = new GooglePR();
    echo "Google Page Rank for $url: ". $pr->get_google_pagerank($url) ;
?>

Which will result in something like this:


Google Page Rank for www.tweaking4all.com: 4

 

How are we going to store our variables?

Now that we know how to retrieve both Google Page Rank and Alexa Ranking, time to look how we can store these values in WordPress.

WordPress has a neat set of functions to store values for your website.

WordPress – Store your own options
 Function Purpose
 add_option() Create/Add a new “option” (name and value pair)
 get_option() Retrieve a stored value/option
 update_option()  Update the value of an “option”

These “option” functions allow you to save a name-value pair in a safe way in your WordPress database. This is site specific, which means, if you have a WordPress MultiSite setup, and you add an option to site A, then it will not interfere with a same named option for site B.

The simplified way of using these functions is:


1
2
3
4
5
6
7
8
9
10
11
12
13
// add a name-value pair to the database
add_option('name_of_my_variable','value of my variable');

// get the value of a name-value pair
// echoes: value of my variable
echo get_option('name_of_my_variable');

// update a name-value pair
update_option('name_of_my_variable','new value of my variable');

// get the value of a name-value pair
// echoes: new value of my variable
echo get_option('name_of_my_variable');

If you’re interested in seeing these value from the admin pages, try this link, which will list “option” name-value pairs:

http://<your website URL>/wp-admin/options.php

 

Combining the goodies: PHP script for daily Google Page Rank and Alexa (global) Score

Now comes the fun part …

We want to run a function, each time a page is being loaded (advanced users may consider a cron job).

In this function we check if our option name-value pairs already exist,
if not: create them with a default value (00.00.00 and 0).
Then check if the stored date value matches “today”,
and if not: update all values for today.

For this I have defined 3 name-value pairs:

t4a_rating_date, which holds the date when we last retrieved the rankings in the format mm.dd.yy,
t4a_rating_google, which holds todays Google Page Ranking, and
t4a_rating_alexa, which holds todays Alexa Ranking score, with thousands separator (!).

To be clear, I have stored the “prclass.php” and “awis_urlinfo.php” files, that we used to determine the Alexa and Google Page Rank, in my WordPress theme directory, and the following code has been added to the “functions.php” file of that WordPress theme.

If you stored these files elsewhere, then make sure to adjust the includes in the PHP code accordingly.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function t4a_do_website_ratings() {
    $url = site_url();
    $url = substr($url(), strpos($url, '//')+2);
 
    // option missing, add date 00.00.00 and rating zero
    if(get_option('t4a_rating_date') === FALSE)   { add_option('t4a_rating_date', '00.00.00' ); }
    if(get_option('t4a_rating_google') === FALSE) { add_option('t4a_rating_google', '0' ); }
    if(get_option('t4a_rating_alexa') === FALSE)  { add_option('t4a_rating_alexa', '0' ); }
   
       
    // We only update this value once a day, no need to do it more often
    if(get_option('t4a_rating_date')!=date("m.d.y")) {
        // update
        update_option('t4a_rating_date', date("m.d.y") );
       
            // ***** Get Google rank *****
        include('prclass.php');
        $pr = new GooglePR();
        update_option('t4a_rating_google', $pr->get_google_pagerank($url));
       
        // ***** Get Alexa rank *****
        include('awis_urlinfo.php');
 
        $urlInfo = new UrlInfo("ABGV$VSNDGFJMSNBBAAB", "A03bahPpcTcHA8+xbK+1x81JllhxC30BCXb+AA0bx", $url));
        $alexa = $urlInfo->getUrlInfo();
 
        update_option('t4a_rating_alexa', number_format(floatval($alexa),0) );
    }
}

Note that the key and secret key in this example are made up, so they will not work – you will have to get your own!

Now comes the question where you would like to call this function (t4a_do_website_ratings()).
We have to make sure it’s called each time a page is being loaded.

You could consider adding this to “header.php” or “footer.php” of your theme, or (and this is what I did) when you actually want to retrieve the Page Rankings to be displayed on your website. So in my case I call this function just before I try to retrieve the first Page Rank value.

So how do we retrieve the page ranking values?
Simple:


1
2
echo get_option('t4a_rating_alexa');
echo get_option('t4a_rating_google');

If you’d be using the method I have used, this would look something like this:


1
2
3
4
5
6
7
8
9
10
11
12
// Make sure we have updated today
set_website_ratings();
       
// Get Alexa rank
$alexa=get_option('t4a_rating_alexa');
       
// Get Google rank
$google=get_option('t4a_rating_google');

// Display the rankings
echo '<p>Alexa Rank: '.$alexa.'</p>';
echo '<p>Google Rank:'.$google.'</p>';

And that’s all there is to it …

If you’d like to update more frequently, say every six hours, then just modify the function as shown below, where the variable $frequency_hours is the “wait” time (6 hours), and the option “t4a_rating_hour” holds the hour when we retrieved the data the most recent. I have highlighted the added/changed lines:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function t4a_do_website_ratings() {
        $frequency_hours = 6; // run every six hours
        $url = site_url();
        $url = substr($url(), strpos($url, '//')+2);

        // option missing, add date 00.00.00 and rating zero
        if(get_option('t4a_rating_date') === FALSE)   { add_option('t4a_rating_date', '00.00.00' ); }
        if(get_option('t4a_rating_hour') === FALSE)   { add_option('t4a_rating_hour', '0' ); }
        if(get_option('t4a_rating_google') === FALSE) { add_option('t4a_rating_google', '0' ); }
        if(get_option('t4a_rating_alexa') === FALSE)  { add_option('t4a_rating_alexa', '0' ); }

       
        // We only want to update (appr.) 4x a day (ie. 6 hours)
        if( (get_option('t4a_rating_date')!=date("m.d.y") ) or (get_option('t4a_rating_hour')+$frequency_hours<=date("G")) ) {
            // update
            update_option('t4a_rating_date', date("m.d.y") );
            update_option('t4a_rating_hour', date("G") );
       
            // ***** Get Google rank *****
            include('prclass.php');
            $pr = new GooglePR();
            update_option('t4a_rating_google', $pr->get_google_pagerank($url));
       
            // ***** Get Alexa rank *****
           include('awis_urlinfo.php');
 
           $urlInfo = new UrlInfo("ABGV$VSNDGFJMSNBBAAB", "A03bahPpcTcHA8+xbK+1x81JllhxC30BCXb+AA0bx", $url));
           $alexa = $urlInfo->getUrlInfo();
 
           update_option('t4a_rating_alexa', number_format(floatval($alexa),0) );
        }
}

Webucator Training Video

Webucator has been kind enough to create a very good looking training video based on this article.
Thank you Lee and Chris for the opportunity!

You can see it below, or on YouTube.
Feel free to explore their YouTube Channel for more interesting Training Video’s.

Support Us ...


Your support is very much appreciated, and can be as easy as sharing a link to my website with others, or on social media.

Support can also be done by sponsoring me, and even that can be free (e.g. shop at Amazon).
Any funds received from your support will be used for web-hosting expenses, project hardware and software, coffee, etc.

Thank you very much for those that have shown support already!
It's truly amazing to see that folks like my articles and small applications.

Please note that clicking affiliate links, like the ones from Amazon, may result in a small commission for us - which we highly appreciate as well.

Comments


There are 2 comments. You can read them below.
You can post your own comments by using the form below, or reply to existing comments by using the "Reply" button.

  • Jul 29, 2016 - 5:14 AM - hans - Author: Comment Link

    UPDATE:

    It looks like Google Ranking is dead (see this link), the function in this article will still work just fine though.
    Some pages suddenly return a ranking of zero … they will just remain hidden anyway if you try to catch a ranking >0.

    Reply

    hans

  • Aug 13, 2017 - 1:13 PM - hans - Author: Comment Link

    UPDATE:

    Amazon enforces HTTPS per 8/24/2017, so I modified the code to work with HTTPS.

    Also note: anything Google rating related can be removed since it is no longer supported by Google.

    Reply

    hans



Your Comment …

Do not post large files here (like source codes, log files or config files). Please use the Forum for that purpose.

Please share:
*
*
Notify me about new comments (email).
       You can also use your RSS reader to track comments.


Tweaking4All uses the free Gravatar service for Avatar display.