forked from Cyber-Duck/laravel-wp-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWpApi.php
executable file
·112 lines (83 loc) · 2.69 KB
/
WpApi.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php namespace Cyberduck\LaravelWpApi;
use GuzzleHttp\Client;
class WpApi
{
protected $client;
public function __construct($endpoint, Client $client, $auth = null)
{
$this->endpoint = $endpoint;
$this->client = $client;
$this->auth = $auth;
}
public function posts($page = null)
{
return $this->_get('posts', ['page' => $page]);
}
public function pages($page = null)
{
return $this->_get('posts', ['type' => 'page', 'page' => $page]);
}
public function post($slug)
{
return $this->_get('posts', ['filter' => ['name' => $slug]]);
}
public function page($slug)
{
return $this->_get('posts', ['type' => 'page', 'filter' => ['name' => $slug]]);
}
public function categories()
{
return $this->_get('taxonomies/category/terms');
}
public function tags()
{
return $this->_get('taxonomies/post_tag/terms');
}
public function category_posts($slug, $page = null)
{
return $this->_get('posts', ['page' => $page, 'filter' => ['category_name' => $slug]]);
}
public function author_posts($name, $page = null)
{
return $this->_get('posts', ['page' => $page, 'filter' => ['author_name' => $name]]);
}
public function tag_posts($tags, $page = null)
{
return $this->_get('posts', ['page' => $page, 'filter' => ['tag' => $tags]]);
}
public function search($query, $page = null)
{
return $this->_get('posts', ['page' => $page, 'filter' => ['s' => $query]]);
}
public function archive($year, $month, $page = null)
{
return $this->_get('posts', ['page' => $page, 'filter' => ['year' => $year, 'monthnum' => $month]]);
}
public function _get($method, array $query = array())
{
try {
$query = ['query' => $query];
if($this->auth) {
$query['auth'] = $this->auth;
}
$response = $this->client->get($this->endpoint . $method, $query);
$return = [
'results' => $response->json(),
'total' => $response->getHeader('X-WP-Total'),
'pages' => $response->getHeader('X-WP-TotalPages')
];
} catch (\GuzzleHttp\Exception\TransferException $e) {
$error['message'] = $e->getMessage();
if ($e->getResponse()) {
$error['code'] = $e->getResponse()->getStatusCode();
}
$return = [
'error' => $error,
'results' => [],
'total' => 0,
'pages' => 0
];
}
return $return;
}
}