Date

Query posts based on Advanced Custom Field values by Registering a Custom “where” Argument

If you manage custom fields in WordPress using Advanced Custom Fields, and you want to use WPGraphQL to get a list of posts filtering by the ACF field value, you’ll need to implement a few things in your themes functions.php.

Summary:

  • Register a new “where” argument to the WPGraphQL Posts connection
  • Filter the Posts connection resolver to account for this new argument

Register the new “where” argument:

First you need to create a add_action on graphql_register_types that will look something like the following code snippet. Here we register a field on the RootQueryToMyCustomPostTypeConnectionWhereArgs where you can define MyCustomPostType as your post type. The type we register will be an ID (This can also be of type Boolean, Float, Integer, orString) for my case I wanted to get only posts that where connected to an other post via the ACF post object field (the field was set to return only the Post ID).

Filter the connection resolver

add_action('graphql_register_types', function () {

    $customposttype_graphql_single_name = "MyCustomPostType";

    register_graphql_field('RootQueryTo' . $customposttype_graphql_single_name . 'ConnectionWhereArgs', 'postObjectId', [
        'type' => 'Int',
        'description' => __('The databaseId of the post object to filter by', 'your-textdomain'),
    ]);
});

Next we have to create an add_filter to graphql_post_object_connection_query_args. If you are familiar with WordPress loops via WP_Query, here we set the $query_args like we would do on any other loop, but we check for your custom where:.

add_filter('graphql_post_object_connection_query_args', function ($query_args, $source, $args, $context, $info) {

    if (isset($args['where']['postObjectId'])) {
        $query_args['meta_query'] = [
            [
                'key' => 'myCustomField',
                'value' => (int) $args['where']['postObjectId'],
                'compare' => '='
            ]
        ];
    }

    return $query_args;
}, 10, 5);

The key will be the name of the field, the value will be the value you will give the postObjectId: "123" in your query, speaking of the query that will ook something like

query GetMyCustomPostType {
  MyCustomPostType(where: {postObjectId: "123"}) {
    nodes {
      title
    }
  }
}

This will get all your MyCustomPostType where myCustomField = 123