Gatsby: Using GraphQL Query on Custom Post Type with Custom Taxonomy

纵饮孤独 提交于 2019-12-07 23:47:28
Tonyeli Tay

What you are looking for is a custom normalizer.

There is a great example on the gatsby-source-wordpress page which is quite similar to what you want to achieve.

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.

Something like this:

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;
        },
    )
);

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.

Remember to run gatsby develop afterwards so as to start/restart your development server.

You need to include name in the query:

{
    wordpressWpPortfolio {
       title
       slug
       id
       portfolio_categories {
          id
          name
       }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!