简体   繁体   中英

Gatsby and WordPress graphQL : query multiple images by id

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!

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
            }
        }
    }
}

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM