My current number of downloads is; 504,607
For my new website that I launched a couple months ago I included a ‘live’ download counter from my WordPress.org plugins. There are a couple ways of adding a counter like that on your site, and one way would be to download and use a existing plugin from the repository; WP Plugin Repo Stats. My preferred way however is not to include yet another plugin on my site for something like that.
A peace of code
Instead I created 3 functions whom are doing everything for me. I’ll be sharing the code to do this in the most basic form which is working for me.
Getting the actual data
To start with we need to get the data from the WordPress.org API. In the following code I’m getting and returning the raw response. There is a ‘author’ field that is set to ‘sormano’ (my w.org nickname) you can change that to your own username.
As you can see, only the ‘downloaded’ is set to ‘true’ in the list of ‘fields’. There is still some default other data that is being returned. Here is a example response of the base (shortened to only include one plugin);
Saving the data
On itself that code doesn’t do much, its currently not saved, it just returns the response. In order to save the response I’ve created a WordPress CRON job by scheduling an event. I’ve chosen to set a daily CRON as this would meet my needs to update the download count on a daily basis. You can also use a lower recurrence if you’d like as the download count is returned on a real-time download count basis. Default valid values here are;
In this example I’m saving the entire request, depending on your exact needs you might like to only save the total download count to save a little bit of extra resources.
Display the total download count
To display the total download count I created a simple shortcode. I like to display the cumulative download count, but you can also simply display the download count of a single plugin.
Thats it! Combine those three peaces of code, and you can simply get your own plugin download count!
Cron vs. Transient
In the past I’ve done the same as above only then by using transients instead of a CRON event. Via transients the download would be gotten from the WordPress.org API whenever they were not found in the database. This was working very well, but also had a couple of disadvantages. Most importantly is that transients get deleted automatically after they expire, and the next time they were not found, it would be a user requesting the particular page. Resulting in a possible API call when a visitor visits a page, which would then lead to a slow loading page.
Using a CRON event the API call will be ran on the background and no visitors will ever notice anything of that. Besides that, if for some reason the API is unavailable, the result isn’t deleted from the database immediately (although it would require some extra code in the above example).