NEW! WPGraphQL for Advanced Custom Fields

Interact with ACF Field data using GraphQL Queries

Using GraphQL Queries in PHP within your WordPress Theme or Plugin

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.
wpgraphql-basic-shortcode-example
Example shortcode that outputs a list of posts and is populated with the site’s content with a GraphQL query
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:
add_shortcode( 'graphql_basic_post_list', function( $atts ) {
  return ! empty ( $output ) ? $output : '';
} );
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 = '
query basicPostList($first:Int){
   posts(first:$first){
      edges{
         node{
            id
            title
            date
         }
      }
   }
}
';

$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):
[data] => Array (
	[posts] => Array (
		[edges] => Array (
			[0] => Array (
				[node] => Array (
					[id] => cG9zdDoyOTI0
					[title] => Test GraphQL Basic Post List
					[date] => 2017-08-19 14:49:25
                )
            )
            [1] => Array (
				[node] => Array (
					[id] => cG9zdDoyOTE3
					[title] => Test Color Field
					[date] => 2017-08-11 19:42:10
                    )
                )
            [2] => Array (
				[node] => Array (
					[id] => cG9zdDoyODc0
					[title] => Denverpost Content in Gutenberg
					[date] => 2017-08-04 21:22:17
                )
            )
            [3] => Array (
				[node] => Array (
					[id] => cG9zdDoyNDA3
					[title] => Fieldmanager Test, yo
					[date] => 2017-06-28 16:25:13
                )
            )
            [4] => Array (
				[node] => Array (
					[id] => cG9zdDoyMzg2
					[title] => Testing a Gutenburg(sp?) Post
					[date] => 2017-06-23 21:02:57
                )
            )
        )
    )
)
This data looks pretty easy to work with! Now we just need to loop through the data and return our markup.
$edges = ! empty( $data['data']['posts']['edges'] ) ? $data['data']['posts']['edges'] : [];

if ( ! empty( $edges ) && is_array( $edges ) ) {
   $output = '<ul>';
   foreach ( $edges as $edge ) {
      $node = ! empty( $edge['node'] ) ? $edge['node'] : '';
      if ( ! empty( $node ) && is_array( $node ) ) {
         $output .= '<li id="' . $node['id'] . '">' . $node['title'] . ' ' . $node['date'] . '</li>';
      }
   }
   $output .= '</ul>';
}
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:
add_shortcode( 'graphql_basic_post_list', function( $atts ) {
   $query = '
   query basicPostList($first:Int){
      posts(first:$first){
         edges{
            node{
               id
               title
               date
            }
         }
      }
   }
   ';

   $variables = [
      'first' => ! empty( $atts['first'] ) ? absint( $atts['first'] ) : 5,
   ];

   $data = do_graphql_request( $query, 'basicPostList', $variables );

   $edges = ! empty( $data['data']['posts']['edges'] ) ? $data['data']['posts']['edges'] : [];

   if ( ! empty( $edges ) && is_array( $edges ) ) {
      $output = '<ul>';
      foreach ( $edges as $edge ) {
         $node = ! empty( $edge['node'] ) ? $edge['node'] : '';
         if ( ! empty( $node ) && is_array( $node ) ) {
            $output .= '<li id="' . $node['id'] . '">' . $node['title'] . ' ' . $node['date'] . '</li>';
         }
      }
      $output .= '</ul>';
   }

   return ! empty( $output ) ? $output : '';
});
NOTE: this post was written using Gutenberg v0.9.0

WPGraphQL at WordCamp for Publishers

I hosted a workshop on “Content Syndication with the WP REST API and WPGraphQL” at the first ever WordCamp for Publishers on Friday, August 18, 2017 at the Denver Post building in beautiful Denver, CO. Unfortunately, there was no video of the workshop, but the slides for the workshop are here: http://slides.com/jasonbahl-1/content-syndication In the workshop, we covered how Digital First Media uses the WP REST API to syndicate millions of pieces of content per year across various WordPress and non-WordPress systems. We cover what we’ve learned about using REST, both positives and negatives. We looked at many of the frustrations we have with working with REST and how GraphQL eases some of those frustrations. We looked at what GraphQL is, how it applies to WordPress as an application data graph, and how you can use GraphQL today in WordPress with the WPGraphQL plugin. We walked through various features of GraphQL using the GraphiQL IDE. We explored the documentation that is generated for the GraphQL Schema using the GraphiQL documentation browser, then we wrote some queries. We queried for posts, posts with nested author objects and nested posts of that author. We looked at node queries, fragments, aliasing, variables and the cursor based pagination, even for data that’s typically not paginated, such as plugins and themes. We then looked at examples of how to extend the WPGraphQL schema to add custom entry points into the queryable WordPress Application Data Graph. The examples we looked at for extending the Schema included:
  • adding a root field
  • adding a custom field to the “post” schema
  • registering a custom post type with WPGraphQL support
  • registering a custom taxonomy with WPGraphQL support
  • adding a custom field to a custom post type where the field can be queried and mutated
  • adding a root field that resolves data from an external system (return a random “dad joke” from icanhazdadjoke.com (source code)
  • Finally, we looked at registering a new Type to the GraphQL schema.
    • We registered a “Syndicated Books” type which resolves with data from external WPGraphQL enabled servers.
The examples we looked at all exist in a plugin here: https://github.com/wp-graphql/wordcamp-for-publishers-demo-extension WPGraphQL is also going to be one of the projects for Contributor Day at WordCamp for Publishers on Saturday, August 19, 2017 at The Denver Post building. Even if you can’t make it to Denver, feel free to contribute remotely…you can submit issues, start working on pull requests for open issues, test the plugin on your own and write a blog post about it, or just simply star the GitHub repo and tweet about it.  

Optimizing WPGraphQL for WordPress VIP

EDIT: This specific issue has been addressed by WordPress core in version WordPress 4.8, but it still shows how to filter to override resolvers in WPGraphQL.

If you host your site with WordPress.com VIP, you can (and should) take advantage of the cached functions they provide to improve the performance of some WordPress core uncached functions.

If you’re using WPGraphQL in a WordPress.com VIP environment and want to have WPGraphQL take advantage of some of these functions, you can do so pretty easily.

In WPGraphQL, the TermObjectType, which is used for terms (categories, tags, custom taxonomies) has a link field, which uses the uncached function: get_term_link in the resolver.

WordPress.com VIP provides an alternative cached function: wpcom_vip_get_term_link.

Our goal here is to:

  • Find all termObjectTypes
  • Filter the resolver for the `link` field on those types, replacing the default resolver with our optimized resolver.

Let’s do this:

First, let’s only hook our functionality in after the Allowed Taxonomies have been registered and setup for WPGraphQL to make use of.

add_action( 'graphql_generate_schema', 'your_prefix_filter_term_object_fields', 10, 1 );

Now, let’s get the Taxonomies that are registered as allowed to show in GraphQL, and we’ll loop through them and filter their fields.

function your_prefix_filter_term_object_fields() {
  
  // Get the allowed taxonomies (taxonomies with "show_in_graphql" => true)
  $allowed_taxonomies = \WPGraphQL::get_allowed_taxonomies();
  
  // Loop through the allowed taxonomies, so that we can filter the fields for each termObjectType for each taxonomy
  if ( ! empty( $allowed_taxonomies ) && is_array( $allowed_taxonomies ) ) {

     foreach( $allowed_taxonomies as $taxonomy ) {

         // Get the taxonomy object as we'll need the "graphql_single_name" property to use in the filter
         $tax_object = get_taxonomy( $taxonomy );

         if ( ! empty( $tax_object->graphql_single_name ) ) {
             add_filter( "graphql_{$tax_object->graphql_single_name}_fields", 'your_prefix_replace_term_link_resolver', 10, 1 );
         }
     }
}

Now, we’re at a point where each TermObjectType (category, tag, etc) will have its fields filtered. So now we need to alter the $fields to replace the resolver for the link field to make use of the cached function we have available in the VIP environment.

// This is the callback for our filter on the termObjectType fields. 
// We get the $fields passed to us and we want to replace the "resolve" function for the "link" field
function your_prefix_replace_term_link_resolver( $fields ) {
    if ( ! empty( $fields['link'] ) ) {
        $fields['link']['resolver'] = function( \WP_Term $term, $args, $context, $info ) {

            // Get the term link using the VIP cached function
            // You could even wrap this with a "function_exists( 'wpcom_vip_get_term_link' )" and fall back to the standard "get_term_link" function
            // to make sure things work when running in an environment where the VIP functions are not present
            $term_link = wpcom_vip_get_term_link( $term->term_id );

            // If the response was valid, return it, otherwise return a null response. 
            // You might also want to throw an exception if the response was a WP_Error
            return ( ! empty( $term_link ) && ! is_wp_error( $term_link ) ) ? $term_link : null;
        
        }
    }

   // Return the $fields, altered or not
   return $fields;
}

There we have it. We now have our link field on TermObjects resolving using a WordPress.com VIP cached function!

Now, we can execute a query like so and know that the link field will be more performant.

{
  tags{
     edges{ 
       node{
          id
          name
          link
       }
     }
  }
}

 

Query Dad Jokes with WPGraphQL

If you’ve ever wanted to use GraphQL to query dad jokes, look no further.

If you’re running a WordPress site, you can install the WPGraphQL plugin along with the WPGraphQL Dad Jokes plugin, and you can query for a random Dad Joke using GraphQL!

The plugin uses icanhazdadjoke.com to retrieve a random dad joke.

This also serves as a great example on how to extend WPGraphQL to customize the Schema for your needs.

The beauty of GraphQL is the data that resolves can come from anywhere. Even though it’s a WordPress plugin, the data that’s queried and resolved, doesn’t have to live in WordPress!

Enjoy!

WordCamp Orange County Recap

I had the privilege of leading a Workshop this weekend at WordCamp Orange County on building Single Page Apps with React, Apollo, WordPress and WPGraphQL.

Denver WordPress Developer Meetup Workshop Follow Up

In preparation for the Workshop I’ll be doing at WordCamp Orange County next weekend, I hosted the Workshop for the Denver WordPress Developer Meetup to get some practice.

I learned a lot about how I need to have my files organized for the workshop and learned what steps I can skip to get through the “important” steps within the allotted time.

If you attended and have feedback, please share. I’m far from a seasoned professional when it comes to public speaking and hosting workshops, so any feedback is welcome.

Anyway, below are some links from the Workshop:

I plan on updating the Tutorial series to have a video walkthrough for each step to compliment the written tutorial, so keep an eye out for that in the next few weeks.

There’s also a wp-graphql slack organization if you’re interested in discussing the plugin more: https://slackin-wpgraphql.herokuapp.com/ (if that link doesn’t work message me and I’ll invite you to the Slack org)