Software Developer

JavaScript Example: Get Plugin Directory Stats From WordPress.org API

This is a quick example of how to query the WordPress.org API using JavaScript. For this example, I will query the WordPress Plugins Directory, but you may modify this to query any of the WordPress.org APIs.

This example uses JavaScript and jQuery. (You may instead prefer to do this using PHP.)

I will also show you how to display the plugin data in a table created with JavaScript and jQuery. You will be able to display this data table with a shortcode.

For this example, I will get a list of the newest plugins that have just been added to the directory.

My example works as is, but you can modify some lines in the JavaScript for your own use case. These are the lines that you may want to modify:

  • Line 4. This is a list of the fields that I want to get and display in a table. These must be keys for fields that are returned by the WordPress.org API request. For example, you could choose to show the “last_updated” field, or “rating” field, or the “short_description” field. Note: If you decide to show the rating field, you should know that it’s given as a percent rating. So, you can convert it to a star rating like this:

    $rating = $percent_rating / 100 * 5;
  • Line 6. This is a list of the column headings for my table. If you modify this, make sure that these headings match the key fields from the previous line.
  • Line 23. You may want to change 250 to a smaller number. This is the number of plugins that will be retrieved. In all my tests, I have found that 250 is the maximum allowed for one request to the WordPress.org API.
  • Line 24. I have the browse parameter set to new. This is because I want to get a list of the absolute newest plugins. You can change the new to popular, updated, or top-rated. Or, you could change browse to tag to search by the plugin tag. Or, you could change browse to author to search by the plugin author. Or, you could change browse to search to search by a general search term.
  • Lines 48–51. I’m sorting this list by the date the plugin was added. The order is descending, so that the newest plugins are shown at the top. You may prefer your own sorting method. Or you can remove these lines completely to leave the data sorted in whatever order it is retrieved.

Here is the JavaScript

Code block 1

(function( $ ) {
	"use strict";

	var pluginFieldKeys = ['added', 'name', 'author', 'active_installs'];

	var tableHeadings = ['Added', 'Plugins', 'Author', 'Active Installs'];

	// Get the count of columns.
    var columnCount = tableHeadings.length;

	// The count of plugins.
	var pluginsCount;

	// Fetch stats from WordPress.org API

	$.ajax({
		url: 'https://api.wordpress.org/plugins/info/1.1',
		type: 'GET',
		data: {
			action: 'query_plugins',
			timeout: 15,
			request: {
				per_page: 250, // 250 is the max allowed
				browse: 'new',
				fields: {
						sections: false,
						description: false,
						homepage: false,
						ratings: false,
						requires: false,
						downloaded: false,
						tags: false,
						donate_link: false,
						active_installs: true
				}
			}
		},
		dataType: "jsonp",
		success: function( data ) {

			// Get the count of plugins.

			var pluginsCount = data.plugins.length;

			// Optional: insert sorting links here.

			// Sort the plugins.
			var sortedPlugins = data.plugins.sort( function (a, b) {
				// Sort by the added date, descending
				return (a.added < b.added) ? 1 : -1;
			});

			// create table

			var table = $('<table>').appendTo('#wp-org-plugins-list');

		    // Add the header row.

			var header = $('<thead />').appendTo(table);

		    for (var i = 0; i < columnCount; i++) {

				$('<th />',{ text: tableHeadings[i] }).appendTo(header);

		    }

		    // Create table body

		    var tBody = $('<tbody />').appendTo(table);

		    // Add the data rows to the table body.

		    for (var i = 0; i < pluginsCount; i++) { // each row

		        var row = $('<tr />').appendTo(tBody);

		        for (var j = 0; j < columnCount; j++) { // each column

					var cellText = sortedPlugins[i][ pluginFieldKeys[j] ];
				
		           	// Remove html from the author name.
			    	if ( 'author' === pluginFieldKeys[j] ) {
			   			cellText = cellText.replace(/<[^>]*>/g, '');
					}

					// Add the cell
					$('<td />',{
					    text: cellText
					}).attr('data-label',tableHeadings[j]).appendTo(row);

		        }
		    }

		}

	});

})( jQuery );

Example Usage

You can display the data on any WordPress page or post with a shortcode. To do this, you must first save the JavaScript from above into a file called call-wp-org-api.js. For this example, the new JavaScript file goes in a plugin folder. You can place the file anywhere you want, but then you must edit the file path on line 5, below (in Code block 2). For example, if you place the file in a child theme, within a js folder, then you would change line 5 (in Code block 2) to this:

wp_register_script( 'call-wp-org-api', esc_url( get_stylesheet_directory_uri() . '/js/call-wp-org-api.js' ), array( 'jquery' ) );

To create the shortcode, add the following PHP functions to your site. This will create the shortcode that will display the plugin data. The JavaScript file will be loaded only on the page that uses that shortcode. It will not be loaded on every page of your site.

Code block 2

/**
 * Register script
 */
function cwpapi_register_script() {
	wp_register_script( 'call-wp-org-api', esc_url( plugins_url( 'call-wp-org-api.js', __FILE__ ) ), array( 'jquery' ) );
}
add_action( 'wp_enqueue_scripts', 'cwpapi_register_script' );

/**
 * Shortcode to show our data list
 */
function cwpapi_shortcode( $atts ) {
	wp_enqueue_script( 'call-wp-org-api' );
 	return '<div id="wp-org-plugins-list"></div>';
}
add_shortcode( 'call_wp_org_api', 'cwpapi_shortcode' );

Now you can use the shortcode, [call_wp_org_api], on a page or post. On that page, you’ll see the table of you data.

Optional Styling

If you want to make the data table mobile friendly, add this CSS to your site.

@media screen and (max-device-width:768px){
  #wp-org-plugins-list td{border:0}
  #wp-org-plugins-list th {border: 0;display: block}#wp-org-plugins-list thead{display:none}
  #wp-org-plugins-list tr{margin-bottom:10px;display:block;border:1px solid #ddd;border-bottom-width:2px}
  #wp-org-plugins-list td{display:block;text-align:right;font-size:13px;border-bottom:1px dotted #ccc}
  #wp-org-plugins-list td:last-child{border-bottom:0}
  #wp-org-plugins-list td:before{content:attr(data-label);float:left;font-weight:700;text-transform: uppercase}
}


Optional: Add Sorting Links

I’ll show you a quick and easy example to add sorting links above the table. This will make the table of plugins data sortable by date, or by the number of active installs, or alphabetically by name.

If you want to add these sorting links, then replace lines 47–51 in the JavaScript above (in Code block 1), with the following.

/* Sorting ----------------------- */

// do we have a sorting query arg?
var sortby = 'date'; // default sort by date
var thisQuery = window.location.search.substring(1);
var thisVars = thisQuery.split("&");
for (var i=0;i<thisVars.length;i++) {
    var pair = thisVars[i].split("=");
    if(pair[0] == 'sort_by'){
    	sortby =  pair[1];
    }
}

// Sort the plugins.
var sortedPlugins = data.plugins.sort( function (a, b) {
	if ( 'installs' == sortby ) {
		// Sort by number of active installs, descending.
		return b.active_installs - a.active_installs;
	} else if ( 'name' == sortby ) {
		// Sort in alphabetical ordery by plugin name, ascending.
		return (b.name.toUpperCase() < a.name.toUpperCase()) ? 1 : -1;
	} else {
		// Sort by the added date, descending
		return (a.added < b.added) ? 1 : -1;
	}
});


// Display the sorting links.

// Paragragh to hold our sorting links.
var p = $('<p />').attr({
	id: 'plugins-data-sort'
}).appendTo('#wp-org-plugins-list');

// Object of available sorts
var sorts = {
	date : 'Date',
	name : 'Name',
	installs : 'Active Installs'
};

// Add each of the sorting links

$.each(sorts, function (index, value) {
	var linkText = 'Sort by ' + value;
 
	if ( sortby == index ) {	// no link for the current sort, just a span
		var currentSort = $('<span />',{
		    text: linkText
		}).appendTo(p);
	} else {

		// Build the sorting URL, upon base url without args or hashes
		var sortHREF = window.location.origin + window.location.pathname + '?sort_by=' + index;

		// @todo optional. 
		// sortHREF += '#plugins-data-sort';// on sort, scroll window to the data

		// Add the link
		$('<a />',{
		    text: linkText,
		    href: sortHREF
		}).appendTo(p);

	}
});

↑ Top

By

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]