Gatsby and WordPress graphQL : query multiple images by id

897 views Asked by At

I am trying to recreate a WordPress slider on Gatsby

I want to see if there is a way to query multiple images by id. I don't want to use many queries but a single one using an array of IDs - if it's possible of course :-)

What the query would be for example if I wanted the 110,200,250,300,400 media of the WordPress library?

Is it more efficient to add the images to my src folder?

Thank you!

2

There are 2 answers

0
Henrik W. On

Considering you are running latest plugin versions


Answer 1

Your query could look something like this:

query ImageQuery {
  allWpMediaItem(filter: {databaseId: {in: [390, 164]}}) {
    nodes {
      localFile {
        childImageSharp {
          gatsbyImageData(layout: CONSTRAINED, formats: [AVIF, WEBP, JPG])
        }
      }
    }
  }
}

Obviously you have to adjust the image options to your needs.


Answer 2

If you actually want to define a set of images to return under a custom query you would need to extend the WPGraphQL schema and return the array of images. The easiest option I can think of is to create a Custom Post Type Slider and add a Repeater field through Advanced Custom Fields. Since ACF is supported with a WPGraphQL Extension it is pretty simple to add it to the schema. You just have to add the Post Type to the schema too. See the docs here: https://www.wpgraphql.com/docs/custom-post-types/

0
Petr Mucha On

I was strugling with similar thing and this query is what worked for me:

query MyQuery {
    mediaItems(where: {in: [10, 12, 14]}) {
        edges {
            node {
                sourceUrl
                srcSet
            }
        }
    }
}