Page 1 of 1

Retrieve Google and Alexa Page Rank for WordPress

Retrieve Google and Alexa Page Rank for WordPress
   13

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.

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.




Article Outdated and Obsolete

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.

 

How to retrieve Alexa Ranking?

With some Google help, and combining and mixing and matching multiple solutions to retrieve the Alexa Ranking, I came to this PHP code/function (note that StackOverflow is an awesome resource!):


1
2
3
4
5
6
7
8
9
function alexa_rank($url){
    $xml = simplexml_load_file("https://data.alexa.com/data?cli=10&url=".$url);
    if(isset($xml->SD->POPULARITY)) {
        return $xml->SD->POPULARITY->attributes()->TEXT;
    }
    else {
        return=0;
    }
}

What this code in essence does is retrieving the related data of a given website in XML format, or returns zero if it somehow failed.

For example, for Tweaking4All, the link would be (you can paste the URL in your browser to see what happens):


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

The resulting XML data could be something like this:


1
2
3
4
5
6
7
8
9
10
11
<!--
Need more Alexa data?  Find our APIs here: https://aws.amazon.com/alexa/
-->
<ALEXA VER="0.9" URL="tweaking4all.com/" HOME="0" AID="5Se4m1d5Wqp3A+" IDN="tweaking4all.com/">
<SD>
<POPULARITY URL="tweaking4all.com/" TEXT="66943" SOURCE="panel"/>
<REACH RANK="75628"/>
<RANK DELTA="+3237"/>
<COUNTRY CODE="US" NAME="United States" RANK="48332"/>
</SD>
</ALEXA>

 

How to retrieve Google Page Rank?

Obsolete – Google Page Rank no longer available … 

Google stopped providing the data needed for this function.
Code below is only provided for reference, but no longer functional.

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:

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

 

Combining the goodies: PHP script for daily Google Page Rank and Alexa 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” file, that we used to determine the Google Page Rank, in my WordPress theme directory, and the following code has been added to the “functions.php” file of that WordPress theme.


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 *****
        $xml = simplexml_load_file("https://data.alexa.com/data?cli=10&url=".$url);
        if(isset($xml->SD->POPULARITY))
            { $alexa = $xml->SD->POPULARITY->attributes()->TEXT; }
        else
            { $alexa=0; }      
        update_option('t4a_rating_alexa', number_format(floatval($alexa),0) );
    }
}

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 *****
            $xml = simplexml_load_file("https://data.alexa.com/data?cli=10&url=".$url);
            if(isset($xml->SD->POPULARITY))
            { $alexa = $xml->SD->POPULARITY->attributes()->TEXT; }
                else
            { $alexa=0; }      
                update_option('t4a_rating_alexa', number_format(floatval($alexa),0) );
        }
}

 

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 13 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.

  • Oct 5, 2015 - 4:57 AM - hans - Author: Comment Link

    UPDATE:

    Updated the code to use the siteurl, instead of the (wrong) name of your blog.
    Cleaned up the code formatting a little bit and added a variant of the function that allows you to retrieve the data more times a day if needed.

    Reply

    hans

  • Nov 19, 2015 - 5:01 AM - John Comment Link

    Awesome post Hans, thanks for taking the time to show the code without needing a plugin!

    Reply

    John

    • Nov 19, 2015 - 5:42 AM - hans - Author: Comment Link

      Thanks John!

      And thank you for taking the time to post a nice feedback – it’s always appreciated. 

      Reply

      hans

  • Mar 12, 2016 - 6:04 AM - hans - Author: Comment Link

    I noticed today the the link “http://data.alexa.com/data?cli=10&url=www.google.com” no longer works.
    I’ll post a possible fix here when I find one.
    Google Rank still works.

    Reply

    hans

  • Mar 14, 2016 - 8:51 AM - hans - Author: Comment Link

    UPDATE:

    I’ve posted a revised article, which describes to do the exact same thing. The difference is that with this new article we utilize the official Alexa Web Information Service (AWIS) API. Read more about it in this new article.

    Reply

    hans

  • Apr 29, 2016 - 7:11 AM - agence web maroc Comment Link

    After I originally commented I appear to have
    clicked the -Notify me when new comments are added- checkbox and from now on whenever a comment is added I receive 4 emails with the exact same comment.
    Is there a means you are able to remove me from that service?
    Appreciate it!

    Reply

    agence web maroc

    • Apr 29, 2016 - 7:20 AM - hans - Author: Comment Link

      I apologize for te unintended inconvenience.
      I’ve removed your email address from the notification.

      As far as I recall, with each notification there should be a link to stop notifications.
      Please let me know if this is not the case. 

      Reply

      hans

  • Sep 21, 2016 - 2:50 AM - Akash - Author: Comment Link

    it is not working for me

    Reply

    Akash

    • Sep 21, 2016 - 8:18 AM - hans - Author: Comment Link

      Hi Akash,

      can you be more specific? 
      Note: Google ranking no longer works. Google dropped support for this.

      Reply

      hans

  • Dec 13, 2018 - 2:58 AM - Shane McDonald - Author: Comment Link

    I tried the link for http://data.alexa.com/data?cli=10&url=www.tweaking4all.com but it just returned ‘Okay’ as the result. I’m wondering has the script changed?

    Reply

    Shane McDonald

    • Dec 13, 2018 - 8:01 AM - hans - Author: Comment Link

      Hi Shane,

      This must have been related to maintenance or something like that at Alexa.com. Just tried the link and got the XML data as expected.
      Note: it’s a good idea to use https:// these days (I’ll update the article).

      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.