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.
Ad Blocking Detected
Please consider disabling your ad blocker for our website. We rely on these ads to be able to run our website. You can of course support us in other ways (see Support Us on the left).
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.
Ad Blocking Detected
Please consider disabling your ad blocker for our website. We rely on these ads to be able to run our website. You can of course support us in other ways (see Support Us on the left).
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:
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.
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):
/**
* Get site info from AWIS.
*/ publicfunction getUrlInfo(){ $queryParams=$this->buildQueryParams(); $sig=$this->generateSignature($queryParams); $url='https://'.self::$ServiceHost.'/?'.$queryParams.'&Signature='.$sig; $ret=self::makeRequest($url); returnself::parseResponse($ret); }
/**
* Builds current ISO8601 timestamp.
*/ protected static function getTimestamp(){ returngmdate("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
*/ protectedfunction 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($paramsas$k=>$v){ $keyvalue[]=$k.'='.rawurlencode($v); } returnimplode('&',$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
*/ protectedfunction generateSignature($url){ $sign="GET\n".strtolower(self::$ServiceHost)."\n/\n".$url; $sig=base64_encode(hash_hmac('sha256',$sign,$this->secretAccessKey,true)); returnrawurlencode($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!
Ad Blocking Detected
Please consider disabling your ad blocker for our website. We rely on these ads to be able to run our website. You can of course support us in other ways (see Support Us on the left).
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):
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:
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
Ad Blocking Detected
Please consider disabling your ad blocker for our website. We rely on these ads to be able to run our website. You can of course support us in other ways (see Support Us on the left).
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.
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');
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:
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:
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');
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 Channelfor 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.
Please consider disabling your ad blocker for our website. We rely on these ads to be able to run our website. You can of course support us in other ways (see Support Us on the left).
Please consider disabling your ad blocker for our website. We rely on these ads to be able to run our website. You can of course support us in other ways (see Support Us on the left).
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.
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.
XSlimmer Awesome tool to get back some of the wasted harddisk space by removing unused application stuff. Highly recommended!
OpenElec The ultimate XBMC distribution. No operating system required, comes completely in a compact form with Embedded Linux, for Intel, AMD, AppleTV, Raspberry Pi, etc.
Lazarus / FPC Lazarus / Free Pascal Compiler - A cross platform software development environment that show similarities with the good old Delphi.
ForkLift Great tool for FTP, SFTP, remote editing of text files (through SSH) and even a great Finder replacement - Not free, but keep an eye on special offerings (I got my copy for $5)
WordPress WordPress is one of the best tools for Blogs and Content Management Systems.
Links Page These and more of our favorite links can be found on the Links Page.
New Downloads
ConnectMeNow4-v4.0.18-macOS-x86-64.dmgDate: 2024-04-24 - Size: 3.5 MBVersion 4 of ConnectMeNow - A tool for more convenient mounting of network shares under macOS. This is the Intel version which works on Intel and Apple Silicon Macs.
ConnectMeNow4-v4.0.18-macOS-arm64.dmgDate: 2024-04-24 - Size: 3 MBVersion 4 of ConnectMeNow - A tool for more convenient mounting of network shares under macOS. This is the Apple Silicon version (not suitable for Intel).
MiniWOL2 MacOS (64 bits Apple Silicon)Date: 2023-08-01 - Size: 1.2 MBminiWol is a simple, but effective application to send Wake On LAN to network devices. This is the signed 64 bit MacOS ARM (Apple Silicon) version.
MovieScanner2-2.2.3-Windows-32bit-setup.exeDate: 2023-04-12 - Size: 18.6 MBA small application that uses FFProbe to scan your video files and logs these details in a small database. This is the 32 bit Windows version.
MovieScanner2-2.2.2-Linux-GTK-64bits.tar.gzDate: 2023-04-11 - Size: 29.2 MBA small application that uses FFProbe to scan your video files and logs these details in a small database. This is the 64 bit Linux version for GTK.
MovieScanner2-2.2.2-Linux-QT5-64bits.tar.gzDate: 2023-04-11 - Size: 29.1 MBA small application that uses FFProbe to scan your video files and logs these details in a small database. This is the 64 bit Linux version for QT5.
Downloads Page Find these and more Downloads on the Downloads Page, where you will also find articles references, operating system requirements and categories.
Amazon Ads
Support us by doing your shopping at Amazon.com, either click the link, or click one of the links below …
You can also sponsor us through these Amazon offerings:
Please consider disabling your ad blocker for our website.We rely on these ads to be able to run our website.You can of course support us in other ways (see Support Us on the left).
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.
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.
hans
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.
hans