mohiohio / graphql-wp
WordPress 的 GraphQL 端点
0.8.5
2020-06-29 09:44 UTC
Requires
- php: >=7
- danielstjules/stringy: 2.4.0
- ivome/graphql-relay-php: 0.5.0
- mohiohio/wordpress-lib: 0.1.5
- ramsey/uuid: 4.0.1
- rbdwllr/reallysimplejwt: 3.0.2
- webonyx/graphql-php: 0.13.8
Requires (Dev)
- analog/analog: ^1.0
- php-stubs/wordpress-stubs: 5.4.0
This package is auto-updated.
Last update: 2024-09-17 09:25:31 UTC
README
一个易于定制的 WordPress GraphQL 端点。
这是一个 WordPress 插件,在 /graphql 提供了一个 GraphQL 端点。
使用此优秀的 graphql-php 库。
支持 Relay 连接。
安装
composer require mohiohio/graphql-wp
如果您不熟悉使用 composer 与 WordPress,我建议使用类似 bedrock 的设置。否则,至少需要 require autoload.php 以使其工作。
使用
探索/开发此插件的最佳方式是在安装后访问 /graphiql
。这将显示可用的端点和参数。注意,这仅在您是登录管理员用户时才有效。
wp_query
此插件旨在遵循 WordPress 现有的 WP Query 函数。因此,您可以像传递给 WP Query* 一样的参数。
*实际上,您可以向 WP_Query 传递很多参数,我只实现了我目前需要的那些。但是添加更多参数是微不足道的,因为参数直接传递给 get_posts 函数,所以只需在模式中定义它们即可。
query example { wp_query { posts(first: 10) { edges { node { title name terms(taxonomy: "category") { name slug } } } } } }
将会给出
{ "data": { "wp_query": { "posts": { "edges": [ { "node": { "title": "Dashboard", "name": "hello-world", "terms": [ { "name": "Uncategorized", "slug": "uncategorized" } ] } } ] } } } }
文章
当然,您也可以获取单个文章
query example { wp_post(ID: 9) { title content status } }
自定义字段
任何元字段都可用,如下所示
query example { wp_post(ID: 9) { title foo: meta_value(key: "foo") bar: meta_value(key: "bar") } }
如果您想定义自己的解析器/类型,可以扩展文章类型的字段模式,如下所示。
// There is a get_{post_type}_schema call available for each post type add_filter('graphql-wp/get_post_schema', function($schema) { $schema['fields'] = function() use ($schema) { // Note call to "parent" function here return $schema['fields']() + [ 'foo' => [ 'type' => Type::string(), 'resolve' => function($post) { return get_post_meta($post->ID, 'foo' ,true); } ], 'bar' => [ 'type' => Type::string(), 'resolve' => function($post) { return get_post_meta($post->ID, 'bar' ,true); } ] ]; }; return $schema; });
自定义文章类型
您可以通过以下方式将自定义文章类型(具有自定义字段)添加到特定客户端的插件中。 graphql-wp/get_post_types 是此操作的不错挂钩。其中 $types
是我们正在工作的模式的哈希,因此只需将新项添加到其中即可。
use GraphQL\Type\Definition\Type; use Mohiohio\GraphQLWP\Type\Definition\Post; use Mohiohio\GraphQLWP\Type\Definition\Attachment; class Foo extends Post { static function getDescription() { return "A custom post type example, for post type `foo`"; } static function getFieldSchema() { return parent::getFieldSchema() + [ 'website' => [ 'type' => Type::string(), 'resolve' => function($post) { return get_post_meta($post->ID,'website',true); }, ], 'image' => [ 'type' => Attachment::getInstance(), 'resolve' => function($post) { $attachment_id = get_post_meta($post->ID,'image',true); return $attachment_id ? get_post($attachment_id) : null; }, ] ]; } } add_filter('graphql-wp/schema-types', function($types){ return array_merge($types, [ Foo::getInstance() ]); });