GraphQL (WP) get a custom post by uri

1.5k Views Asked by At

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:

book(uri: "")

the only option seems:

book(id: "")

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?

2

There are 2 best solutions below

0
On

I used slug with nuxtjs

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);
    } 
  },

here is what worked for me: https://github.com/atazmin/nuxtjs-wordpress/blob/master/nuxt/pages/posts/_slug/index.vue

0
On

The query getBookBySlug has arguments declared somewhere your code (there must be to build the full schema). You need to change those arguments to accept uri instead of id.

Also the function that receives those arguments and returns the books must be able to handle the uri argument and find the correct book in the DB.