Link to WPGraphQL on Github
Link to WPGraphQL on WordPress.org

Optimizing WPGraphQL for WordPress VIP

By Jason Bahl

July 21st, 2017

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.

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.

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.

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.