Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@ericlbarnes ericlbarnes commented Sep 27, 2015

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