Feeding data to blocks in the editor
Content in the the WordPress editor is created via (Gutenberg) blocks, which fetch their data from the server via an API. WordPress core uses the WP REST API, but we can also use Gato GraphQL to power our own blocks.
Let's explore how the block can fetch data from the GraphQL server.
Endpoint
Because blocks are used within the context of the WordPress editor, the user is already logged-in, and hence we can connect to an internal GraphQL endpoint (accessible within the wp-admin only) instead of a public endpoint.
This internal blockEditor
endpoint is accessible under:
This endpoint has a pre-defined configuration (i.e. it does not have the user preferences from the plugin applied to it), so its behavior is consistent.
Conveniently, we can also point to JavaScript global variable GATOGRAPHQL_BLOCK_EDITOR_ADMIN_ENDPOINT
, which contains the endpoint URL.
You can also create your own internal endpoint, and pre-define whatever specific configuration required for your blocks (enabling nested mutations, enabling namespacing, defining what CPTs can be queried, or anything else available in the Schema Configuration).
Alternatively, you can create Persisted Queries and retrieve data from them (instead of from an endpoint). Check out how the client code must be adapted.
fetch
Connecting via
We can use the standard fetch
method to connect to the server.
This JavaScript code submits a query with variables to the GraphQL server, and prints the response to console.
Sending the REST nonce header
If you need to execute an operation including REST nonce, add the X-WP-Nonce
header.
Print a JS variable containing the nonce, via PHP code:
Then include the nonce value in the headers to fetch
:
Connecting via a GraphQL client library
You can also use the GraphQL client library of your choice to connect to the server. Some options are:
Here is an example using GraphQL request:
The Gato GraphQL plugin itself powers its blocks via GraphQL, using the graphql-request
library.
Check out the source code for the "Schema Configuration" block and its data store.