机动/频道

WordPress REST API 的 PHP 库

v0.0.8 2019-02-28 13:24 UTC

This package is auto-updated.

Last update: 2024-09-29 02:18:40 UTC


README

目前仅支持 GET 请求。

目录

安装

通过 composer 安装

composer require maneuver/channel

并包含自动加载器

require('vendor/autoload.php');

快乐时光。🤙

身份验证

基本身份验证

确保已安装并激活了 WordPress 的 基本身份验证 插件。
(如仓库所述,仅用于开发目的)

$channel = new \Maneuver\Channel([
  'uri' => 'http://example.com/wp-json/wp/v2/',
  'username' => 'your-username',
  'password' => 'your-password',
]);

API 令牌

确保已安装并激活了 Rooftop API Authentication 插件。

$channel = new \Maneuver\Channel([
  'uri' => 'http://example.com/wp-json/wp/v2/',
  'token' => 'your-token',
]);

OAuth

目前尚未实现。

使用方法

帖子

检索所有帖子列表(post_type = 'post')

$posts = $channel->getPosts();

echo count($posts);

通过 ID 检索帖子

$post = $channel->getPost(1);

echo $post->excerpt;

使用 Twig?不用担心

<h1>{{ post.title }}</h1>
<p>{{ post.excerpt|raw }}</p>

页面

检索所有页面列表

$pages = $channel->getPages();

foreach ($pages as $page) {
  echo $page->title;
}

通过 ID 检索页面

$page = $channel->getPage(1);

echo $page->content;

分类法与术语

检索所有现有分类法

$taxonomies = $channel->getTaxonomies();

通过 slug 检索一个分类法

$taxonomy = $channel->getTaxonomy('category'); // use singular taxonomy name

// Then you can retrieve its terms:
$terms = $taxonomy->terms();

或使用 'get' 方法在一次调用中检索术语

$terms = $channel->get('categories'); // use plural taxonomy name

用户

获取所有用户

$users = $channel->getUsers();

echo $users[0]->name;

媒体

获取所有媒体

$media = $channel->getMedia();

自定义帖子类型

当您在 WordPress 安装中定义自定义帖子类型时,请确保将 show_in_rest 选项设置为 true。这将在 REST API 中公开一个端点以检索帖子。 阅读文档

add_action('init', function(){

  register_post_type('product', [
    'labels' => [
      'name'          => 'Products',
      'singular_name' => 'Product',
    ],
    'public'        => true,
    'show_in_rest'  => true,
    'rest_base'     => 'products' // defaults to the post type slug, 'product' in this case
  ]);

});

然后使用通用 'get' 方法

$products = $channel->get('products'); // Pass in the 'rest_base' of the custom post type.

稍高级的功能

端点

您实际上可以使用 'get' 方法调用任何端点

$post_types = $channel->get('types');
$latest = $channel->get('posts?per_page=5');

REST API 手册 中了解更多关于所有端点的信息

Guzzle

您可以传递更多 Guzzle 请求选项

$latest = $channel->get('posts?per_page=5', [
  'proxy' => 'tcp://:8125',
]);

这里 了解更多关于 Guzzle 请求选项的信息。

自定义类

每次调用都返回一个扩展 '\Maneuver\Models\Base' 类的对象(或对象数组)。如果需要,您可以定义自己的类。

注意:不要直接扩展 '\Maneuver\Models\Base' 类,否则会丢失一些功能。

class MyPost extends \Maneuver\Models\Post {
  public function fullTitle() {
    return 'Post: ' . $this->title;
  }
}

class MyPage extends \Maneuver\Models\Page {

}

$channel->setCustomClasses([
  // 'type' => 'ClassName'
  // eg: 'user' => 'MyUser'
  // or:
  'post'    => 'MyPost',
  'page'    => 'MyPage',
  'product' => 'MyPost', // custom post type
]);

$post = $channel->getPost(1);

echo $post->fullTitle();

echo get_class($post);
// => 'MyPost'

待办事项

  • 对 ACF 字段的更多支持
  • 对图像的更好支持
  • 添加 WP_Query 类似的参数
  • OAuth 身份验证