Categories
Blogs

I’m following one of the tutorials on youtube on performing basic query on headless wordpress api with GraphQL. The query that the tutorial (over a year old now) does is:


query getBookBySlug($slug: String) {
    book: bookBy(uri: $slug) {
      title
      book_meta{
        price
        publisher
      }
    }
  }

Books/book is a custom pust type and I can query it using the GraphiQL playground in wordpress to see what it returns The problem with the query above is that ir returns null. Also, the bookBy (or postBy) is apprently deprecated (according to the warning I get in GraphiQL suggesting instead post(id: “”) or book(id: “”) in my case. The problem is that I want to query the book by ”uri” not ”id” and there seems to be no option to query:
The uri field exists and is populated. This query in the GraphiQL returns successfully all the required book details:


query getBook {
  book(id: "cG9zdDo0MA==") {
    title
    slug
    uri
    book_meta {
      price
    }
  }
}

How can I change the first function to query a book by uri?


async asyncData({ params }) {
    const data = {
      query: `query GET_POST($slug: String) {
        postBy(slug: $slug) {
          title
          content
          author {
            node {
              name
            }
          }
          featuredImage {
            node {
              caption
              altText
              sourceUrl(size: LARGE)
            }
          }
          date
        }
      }`,
      variables: {
        slug: params.slug
      }
    }

    const options = {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      data: data,
      url: 'http://localhost/graphql'
    };
        
    try {
      const response = await axios(options);
      
      return {
        loadedPost: response.data.data.postBy
      } 
    } catch (error) {
      console.error(error);
    } 
  },

One reply on “GraphQL (WP) get a custom post by uri”

Leave a Reply

Your email address will not be published. Required fields are marked *