Gatsby:在具有自定义分类法的自定义帖子类型上使用GraphQL查询
我正在使用Gatsby为WordPress提供前端并使用GraphQL查询数据.
I am using Gatsby to deliver a front end to WordPress and querying data with GraphQL.
我有一个带有自定义帖子类型和自定义分类法的帖子.
I have a post with a Custom Post Type and a Custom Taxonomy.
但是,当我在CPT上进行查询时,我可以获取自定义分类法的编号,但是却不知道如何检索相应的名称.
However when I query on the CPT, I can get the number of the Custom Taxonomy but no don't know how to retrieve the corresponding names.
以下是我的查询;
{
wordpressWpPortfolio {
title
slug
id
portfolio_categories
}
}
这就是返回的内容;
{
"data": {
"wordpressWpPortfolio": {
"title": "Test Portfolio 1",
"slug": "test-portfolio-1",
"id": "5caf7182-c9f5-53d9-94da-b49cfbdc6d7f",
"portfolio_categories": [
5
]
}
}
}
但是,我无法在GraphQL游乐场中选择其他字段.
However, there are no other fields I can select in the GraphQL playground.
以下是我的预期结果;
Below is my expected result;
{
"data": {
"wordpressWpPortfolio": {
"title": "Test Portfolio 1",
"slug": "test-portfolio-1",
"id": "5caf7182-c9f5-53d9-94da-b49cfbdc6d7f",
"portfolio_categories": [
"id":5,
"name":"portfolio category name"
]
}
}
}
有什么办法可以加入"其余的终点?
Is there any way to "join" the rest end points?
我在做什么错,我该如何解决?
What am I doing wrong and how can I fix It?
您正在寻找的是自定义规范化器.
What you are looking for is a custom normalizer.
gatsby-source-wordpress
与您要实现的页面非常相似的页面.
There is a great example on the gatsby-source-wordpress
page which is quite similar to what you want to achieve.
或者,您可能希望修改CPT REST API以使用register_rest_api()
方法,只要您对WordPress开发感到满意.
Alternatively, you may want modify your CPT REST API to return both the category ID and name of the field using the register_rest_api()
method provided you are comfortable with WordPress development.
类似这样的东西:
register_rest_field(
// Custom Post Type name
'portfolio',
// Name of field being added to your REST API response (portfolio_categories)
'portfolio_categories',
array(
'get_callback' => function( $data ) {
$category_terms = wp_get_post_terms(
$data['id'],
'portfolio_categories'
);
$portfolio_categories = array();
foreach( $category_terms as $term ) {
$portfolio_category_obj = new StdClass();
$portfolio_category_obj->ID = $term->ID;
$portfolio_category_obj->name = $term->name;
array_push(
$portfolio_categories,
$portfolio_category_obj
);
}
return $portfolio_categories;
},
)
);
这将在REST API中添加一个名为portfolio_categories
的额外字段,该字段将返回一个数组,以便您可以按预期使用GraphQL.
This will add an extra field in your REST API to called portfolio_categories
which returns an array so you can use the GraphQL as expected.
请记住,之后再运行 gatsby develop
来启动/重新启动开发服务器.
Remember to run gatsby develop
afterwards so as to start/restart your development server.