Hcabnettek
Hcabnettek

Reputation: 12928

How can I do a WpGraphQL query with a where clause?

This works fine

  query QryTopics {
    topics {
      nodes {
          name
          topicId
          count
      }
    }
  }

But I want a filtered result. I'm new to graphql but I see a param on this collection called 'where', after 'first', 'last', 'after' etc... How can I use that? Its type is 'RootTopicsTermArgs' which is likely something autogenerated from my schema. It has fields, one of which is 'childless' of Boolean. What I'm trying to do, is return only topics (a custom taxonomy in Wordpress) which have posts tagged with them. Basically it prevents me from doing this on the client.

data.data.topics.nodes.filter(n => n.count !== null)

Can anyone direct me to a good example of using where args with a collection? I have tried every permutation of syntax I could think of. Inlcuding

  topics(where:childless:true)
  topics(where: childless: 'true')
  topics(where: new RootTopicsTermArgs()) 
  etc... 

Obviously those are all wrong.

Upvotes: 3

Views: 5292

Answers (1)

Jason Bahl
Jason Bahl

Reputation: 141

If a custom taxonomy, such as Topics, is registered to "show_in_graphql" and is part of your Schema you can query using arguments like so:

query Topics {
  topics(where: {childless: true}) {
    edges {
      node {
        id
        name
      }
    }
  }
}

Additionally, you could use a static query combined with variables, like so:

query Topics($where:RootTopicsTermArgs!) {
  topics(where:$where) {
    edges {
      node {
        id
        name
      }
    }
  }
}

$variables = {
  "where": {
    "childless": true
  }
};

One thing I would recommend is using a GraphiQL IDE, such as https://github.com/skevy/graphiql-app, which will help with validating your queries by providing hints as you type, and visual indicators of invalid queries.

You can see an example of using arguments to query terms here: https://playground.wpgraphql.com/#/connections-and-arguments

Upvotes: 9

Related Questions