Using GraphQL Queries in PHP within your WordPress Theme or Plugin
By Jason Bahl
September 20th, 2017
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:
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
date. The raw data returned from the query should look like this (of course with your site’s data):
This data looks pretty easy to work with! Now we just need to loop through the data and return our markup.
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:
NOTE: this post was written using Gutenberg v0.9.0