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

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


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       }    }}