WPGraphQL for FacetWP
By Hamish Blake
July 18th, 2019
I am pleased to announce the beta release of my FacetWP integration plugin for WPGraphQL.
The main functionality was written quickly in late 2018 to fill a need to provide client-side access to FacetWP’s index and filtering functionality via WPGraphQL. As a proof-of-concept it worked exactly as needed. It was a lot less effort to create this plugin than it would have been to roll my own facet indexing module.
Recently, I have had some down time between changing jobs and have been able to refactor and clean up the original code into something more usable by the larger WordPress and WPGraphQL community. If you have the need to expose the functionality of FacetWP via the GraphQL schema, I hope you find this plugin helpful!
To register WP Post Type(s) to be added to the schema, simply use the facet query registration function register_graphql_facet_type() as follows:
Prerequisites: To use the plugin users must have already configured at least one facet in FacetWP and configured WPGraphQL.
The plugin uses reflection to expose all configured facets are available for querying. Each facet is added as an input argument to the query.
Different facet types have unique inputs (eg a Slider has a min and max while Checkboxes is a simple array of strings).
Given the post registration above the query variables might look something like this:
Registering a facet type will result in a new field on the Root Query. The field name is determined by the type to be queried.
The payload of the new facet field includes:
- facets: The returned facet information
- type connection: A WPGraphQL connection to the post type query
Given the post registration earlier, the query and response payload might look like this:
This payload includes all information relating to the queried facets and input variables. Available choices (including available count), settings and other relevant information are exposed in this field.
This payload is a connection to the configured post type. It accepts all the pertinent GraphQL arguments (paging, sorting etc).
This connection only returns posts that match the facet filter.
This plugin provides users of WPGraphQL with access to an established and popular WordPress plugin for server-side filtering; FacetWP. I hope the WordPress community finds it helpful. It certainly was a great time saver for our project.
Disclaimer and limitations: I have thoroughly tested Checkbox, fSelect and Radio facet types, as these are used in my app. There is provisional support for all other facet types, however these are not fully tested. As with any open source project, a detailed issue (or better yet a pull request) would be appreciated.
Please see GitHub for further documentation and commentary.