Query chartbeat api and cache results - wordpress
php class for querying chartbeats api and caching the results - refresh cache every minute
/*
* Check chartbeat for most read articles
* inside of category you are in
*/
class MostReadChartbeat {
public $host = "yourdomain.co.uk";
public $chartbeat_api_key = "yourapikey_provided_by_chartbeats_in_your_panel";
//main object where the posts from different sections/categories will be stored
public $cats_posts = array();
/* prepare section name string for query */
private function get_section ( $section ) {
return strtolower( preg_replace( '/ / ', '+', $section) );
}
//naming convention - category (wp), section (Chartbeats)
private function query_posts_from_category( $section ) {
$chartbeat_query = 'http://api.chartbeat.com/live/toppages/v3/?apikey=' . $this->chartbeat_api_key . '&host=' . $this->host . '§ion=' . $this->get_section( $section );
/* Query Chartbeat */
$chart_resp = json_decode( file( $chartbeat_query )[0] );
//this obj is storing posts from a certain category for caching purposes
$this_cat_posts = array();
//loop through posts result from single category
foreach( $chart_resp->pages as $post ) {
array_push($this->cats_posts, $post);
array_push($this_cat_posts, $post);
}
//cache the results for specified category for 1 minutes
//to prevent flooding chartbeat with requests
if (sizeof($this->cats_posts) > 0 ) {
set_transient( $this->get_section( $section ), $this_cat_posts, MINUTE_IN_SECONDS );
} else {
set_transient( $this->get_section( $section ), "no_posts", MINUTE_IN_SECONDS );
}
}
private function get_posts_from_cached_category ( $posts ) {
//add posts to the main category posts object
foreach( $posts as $post ) {
array_push($this->cats_posts, $post);
}
}
/* main method initiated after page load
* we pass array of categories as one post may contain several categories
*/
public function get_main_posts( $cats ) {
foreach( $cats as $category ) {
//query chartbeat
$this->add_posts_from_category( $category->name );
}
}
/* method initiated in two cases:
* 1. on page load by "get_main_posts()"
* 2. for other single categories query to meet the aim of geting 10 most read posts
*/
public function add_posts_from_category( $category ) {
/* Check if we have any data about the categories in cache
* check cache for the category key
*/
$cached_category = get_transient( $this->get_section( $category ) );
if ( false === $cached_category ) {
$this->query_posts_from_category( $category );
} elseif ( gettype( $cached_category ) === "array" ) {
$this->get_posts_from_cached_category( $cached_category );
}
}
}
To call it simply create an instance of the class "MostReadChartbeat" and use one of the public methods "get_main_posts($array)" or "add_posts_from_posts($string)" adding proper arguments to query chartbeat and cache results for a minute.
I hope that it's going to save you some time while developing some functionalities. If it helped please give me a shout below.

No comments:
Post a Comment