WPGraphQL doesn't natively support filtering a query for custom post types by their taxonomy.
But, you can add your own clause by adding this code (and adjusting the fields to suit your requirements) in your functions.php file :
// First, we register the field in the "where" clause.
add_action('graphql_register_types', function () {
$customposttype_graphql_single_name = "Country"; // Replace this with your custom post type single name in PascalCase
// Registering the 'categorySlug' argument in the 'where' clause.
// Feel free to change the name 'categorySlug' to something that suits your requirements.
register_graphql_field('RootQueryTo' . $customposttype_graphql_single_name . 'ConnectionWhereArgs', 'categorySlug', [
'type' => [ 'list_of' => 'String' ], // To accept multiple strings
'description' => __('Filter by post objects that have the specific category slug', 'your_text_domain'),
]);
});
// Next, we add a filter to modify the query arguments.
add_filter('graphql_post_object_connection_query_args', function ($query_args, $source, $args, $context, $info) {
$categorySlug = $args['where']['categorySlug']; // Accessing the 'categorySlug' argument.
if (isset($categorySlug)) {
// If the 'categorySlug' argument is provided, we add it to the tax_query.
// For more details, refer to the WP_Query class documentation at https://developer.wordpress.org/reference/classes/wp_query/
$query_args['tax_query'] = [
[
'taxonomy' => 'your_taxonomy', // Replace 'your_taxonomy' with your actual taxonomy key
'field' => 'slug',
'terms' => $categorySlug
]
];
}
return $query_args;
}, 10, 5);
After applying these changes, you should be able to retrieve a list of your custom posts filtered by your taxonomy like this :
query GetCountries {
countries(where: { categorySlug: ["united-states", "france"] }) {
nodes {
id
}
}
}