Get Plugin Download Count from WordPress.org API

Since last 3 days, I have been looking out for a way to get the total download count of my plugin.

But there is almost no information about API for WordPress.org except on http://codex.wordpress.org/WordPress.org_API which is just links and some more information on http://dd32.id.au/projects/wordpressorg-plugin-information-api-docs/ which provides details on WordPress Plugin Information API. So after some tweaking and testing here is the final code to get the download count.

<?php
	$payload = array(
		'action' => 'plugin_information',
		'request' => serialize(
			(object)array(
				'slug' => 'i-recommend-this',
				'fields' => array(
					'downloaded' => true,
					'description' => false
					)
				)
			)
		);

	$body = wp_remote_post( 'http://api.wordpress.org/plugins/info/1.0/', array( 'body' => $payload) );

	$body = unserialize($body['body']);
	echo '<p>Downloaded: ' . print_r( $body->downloaded, true ) . '</p>';


?>

Now to avoid requesting information from WordPress.org on every page load, the required information can be saved in a transient and refreshed once a day.  This is in no way a final code. I have not placed any additional logic to display arrays, etc. So just use this as a starting point.

I will write a plugin to do this but until then if you know a better way, please share your ideas in comments.

Updates

Well it seems there is plugin_api using which most of the things I did above was unnecessary. If we use plugins_api we can get the total download count using few lines of code below:


/** If plugins_api isn't available, load the file that holds the function */
if ( ! function_exists( 'plugins_api' ) )
	require_once( ABSPATH . 'wp-admin/includes/plugin-install.php' );

/** Prepare our query */
$call_api = plugins_api( 'plugin_information',
	array(
		'slug' => 'i-recommend-this'
	)
);

/** Display the results */
if ( is_wp_error( $call_api ) )
	echo '<pre>' . print_r( $call_api->get_error_message(), true ) . '</pre>';
else
	//echo '<pre>' . print_r( $call_api, true ) . '</pre>';
	echo '<p>' . print_r( $call_api->downloaded, true ) . '</p>';

258

1 thought on “Get Plugin Download Count from WordPress.org API”

Leave a Reply to legal document signing app Cancel reply

Your email address will not be published. Required fields are marked *