Skip to content

Instantly share code, notes, and snippets.

@ericlbarnes
Last active September 27, 2015 04:44
Show Gist options
  • Save ericlbarnes/d78d3bc772a454dcbb09 to your computer and use it in GitHub Desktop.
Save ericlbarnes/d78d3bc772a454dcbb09 to your computer and use it in GitHub Desktop.
Example code for pulling the top posts from WordPress API
<?php $popular = (new WordPressApi())->popular(); ?>
<ul>
<?php foreach ($popular as $post): ?>
<li><a href=“<?php echo $post->href; ?>”><?php echo $post->title; ?></li>
<?php endforeach; ?>
</ul>
<?php
class WordPressApi
{
private $site_id = 'your_site_id';
private $token = 'your_api_token';
private $baseUrl;
public function __construct()
{
$this->baseUrl = 'https://public-api.wordpress.com/rest/v1.1/sites/'.$this->site_id.'/';
}
public function popular($period = 'month', $max = 8)
{
$data = $this->getJson($this->baseUrl.'stats/top-posts?period='.$period.'&max='.$max);
foreach ($data->days as $key => $value) {
$posts = array_filter($value->postviews, function($post){
return $post->type == 'post';
});
}
}
public function getJson($url)
{
$options = [
'http' => [
'ignore_errors' => true,
'header' => [
0 => 'authorization: Bearer '. $this->token,
]
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
return json_decode( $response );
}
}
@ericlbarnes
Copy link
Author

See this post for full explanation:
Get The Most Popular Posts From The WordPress API

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment