Skip to content

Instantly share code, notes, and snippets.

@mathetos
Last active August 30, 2018 19:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save mathetos/877eba532a7a5461c3759c0010bfdb9f to your computer and use it in GitHub Desktop.
Save mathetos/877eba532a7a5461c3759c0010bfdb9f to your computer and use it in GitHub Desktop.
Shortcode to display number of 5-star ratings of a plugin on the WordPress.org Plugin Directory (aka Plugin Repo)
<?php
add_shortcode( 'give5stars', 'get_give_five_stars' );
function get_give_five_stars() {
$plugin_slug = 'give';
// Get any existing copy of our transient data
if ( false === ( $cachedresults = get_transient( 'wp-plugin-repo-data-' . $plugin_slug ) ) ) {
// It wasn't there, so regenerate the data and save the transient
$not_cached = 'Not Cached!';
$cachedresults = call_plugin_repo_api($slug=$plugin_slug);
set_transient( 'wp-plugin-repo-data-' . $plugin_slug, $cachedresults, 12 * HOUR_IN_SECONDS );
} else {
$not_cached = 'Cached!';
}
var_dump(get_transient( 'wp-plugin-repo-data-' . $plugin_slug ));
return '<p><strong>"' . ucwords(str_replace("-"," ",$cachedresults->slug)) . '"</strong> currently has <strong>' . $cachedresults->ratings[5] . '</strong> 5-star ratings. And this response is ' . $not_cached . '</p>';
}
function call_plugin_repo_api($slug) {
// Require plugin-install.php to query the Repo correctly
if( !function_exists( 'plugins_api' ) ) {
require_once(ABSPATH . 'wp-admin/includes/plugin-install.php' );
}
// Only get the information we really want from the Repo API
$call_api = plugins_api( 'plugin_information',
array(
'slug' => $slug,
'fields' => array(
//'name' => true, -- required, cannot disable
//'slug' => true, -- required, cannot disable
//'version' => false, -- required, cannot disable
//'author' => false, -- required, cannot disable
//'contributors' => false, -- required, cannot disable
'requires' => false,
'tested' => false,
'compatibility' => false,
'rating' => true,
'num_ratings' => false,
'ratings' => true,
'downloaded' => false,
'last_updated' => false,
'added' => false,
'homepage' => false,
'sections' => false,
'tags' => false,
'active_installs' => false,
'reviews' => false,
//'download_link' => false, -- required, cannot disable
//'donate_link' => false, -- required, cannot disable
) ) );
return $call_api;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment