GraphQL is most popularly known as a way to fetch data from remote sources via HTTP requests, but with WPGraphQL, you can access your local WordPress data in your plugin or theme via declarative GraphQL queries.
An example use case would be a simple shortcode for a list of posts.
Let’s look at how we can build a simple shortcode that populates a list of posts from the site and renders an unordered list with the post’s title and date.
First, lets register our shortcode:
Now we have a [graphql_basic_post_list] shortcode but it’s not useful. Our end goal is to output a list of posts with the title and date, and we’ll use the ID as the “id” of each list item.
Since we know what data we’ll need, we can start with writing our GraphQL query to get the data.
Inside the shortcode function, let’s add our query. GraphQL queries are static strings, so we can simply add:
$query = '
$data = do_graphql_request( $query );
This will give us an array of posts, which contains an array of “edges” and each edge will contain a “node”. The node is our post object, and this is where the fields we requested are. In our case, we asked for id, title, and date.
The raw data returned from the query should look like this (of course with your site’s data):
This makes sure that we have an array of “edges” and if we do, it creates an unordered list and loops through the edges, creating a list item for each node, with the node’s id as the <li> id property, and the post’s title and date as the text within the list item.
The complete shortcode, with an example argument for how many posts to query is: