Last active
September 27, 2015 04:44
-
-
Save ericlbarnes/d78d3bc772a454dcbb09 to your computer and use it in GitHub Desktop.
Example code for pulling the top posts from WordPress API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See this post for full explanation:
Get The Most Popular Posts From The WordPress API