Migrate to Netlify Today

Netlify announces the next evolution of Gatsby Cloud. Learn more

ContactSign Up
Community Plugin
View plugin on GitHub

Note

Please note: the original author of this package is Marc Glasser — see the the original repo and package.

gatsby-source-woocommerce

Source plugin for Gatsby. Pulls in data from protected routes via the WooCommerce REST API with credentials.

Contents

Install

npm install --save @pasdo501/gatsby-source-woocommerce

or

yarn add @pasdo501/gatsby-source-woocommerce

How to Use

// In gatsby-config.js
plugins:[
  {       
    resolve: '@pasdo501/gatsby-source-woocommerce',
    options: {
      // Base URL of Wordpress site
      api: 'wordpress.domain',

      // set to false to not see verbose output during build 
      // default: true
      verbose: true,

      // true if using https. otherwise false.
      https: false,
      api_keys: {
        consumer_key: <key>,
        consumer_secret: <secret>,
      },
      // Array of strings with fields you'd like to create nodes for...
      fields: ['products', 'products/categories', 'products/attributes'],
      // Send the API keys as query string parameters instead of using the authorization header
      // OPTIONAL: defaults to false
      query_string_auth: false,
      // Version of the woocommerce API to use
      // OPTIONAL: defaults to 'wc/v3'
      api_version: 'wc/v3',
      // OPTIONAL: How many results to retrieve *per request*
      per_page: 100,
      // OPTIONAL: Custom WP REST API url prefix, only needed if not using 
      // the default prefix ('wp-json').
      // wpAPIPrefix: 'wp-json',
      // OPTIONAL: Support for URLs with ports, e.g. 8080; defaults to no port
      // port: '8080',
      // OPTIONAL: Encoding; default to 'utf8'
      encoding: 'utf8',
      // OPTIONAL: Custom Axios config (see https://github.com/axios/axios) - note that this can override other options.
      axios_config: {
        // Axios config options
      }
    }
  }
]

Currently Supported Fields

Definitive:

  • Products
  • Products Attributes
  • Categories
  • Customers
  • Orders
  • Reports
  • Coupons

Note: If following the endpoint layout from the WooCommerce REST API docs, all fields that do not contain a wildcard should be supported.

For example, to get product categories: including ‘products/categories’ in fields will show up as allWcProductsCategories / wcProductsCategories

Some GraphQL Query Examples

All products (with associated images):

{
  allWcProducts {
    edges {
      node {
        id
        wordpress_id
        name
        categories {
          wordpress_id
        }
        images {
          localFile {
            // childImageSharp ... etc
          }
        }
      }
    }
  }
}

All products attributes with terms:

{
  allWcProductsAttributes {
    nodes {
      name
      wordpress_id
      order_by
      position
      slug
      type
      has_archives
      attribute_options {
        count
        description
        menu_order
        name
        slug
      }
    }
  }
}

All product categories (with associated image):

{
  allWcProductsCategories {
    edges {
      node {
        id
        wordpress_id
        name
        slug
        image {
          localFile {
            // childImageSharp ... etc
          }
        }
      }
    }
  }
}

Specific product by wordpress ID:

{
  wcProducts(wordpress_id: {eq: 12}) {
    name
    price
    related_ids
  }
}
{
  wcProducts(wordpress_id: {eq: 12}) {
    name
    price
    related_products {
      name
      // etc - same fields as a normal product
    }
  }
}
{
  wcProducts(wordpress_id: {eq: 12}) {
    name
    price
    grouped_products_nodes {
      name
      // etc - same fields as a normal product
    }
  }
}

Specific product, with variations:

{
  wcProducts(wordpress_id: {eq: 12}) {
    wordpress_id
    name
    price_html
    product_variations {
      # Note: ID, not wordpress_id
      id 
      # Note: no price_html inside variations
      price 
      description
      attributes {
        # The compination of attributes making up this variation. Missing attribute = any
        name
        option
      }
    }
    
  }
}

Specific product category (with associated products):

{
  wcProductsCategories(wordpress_id: {eq: 20}) {
     name
     slug
     products {
       name
       price
       images {
         localFile {
           // childImageSharp ... etc
         }
       }
     }
   }
}

All Product Tags and their associated products:

{
  allWcProductsTags {
    nodes {
      name
      count
      products {
        name
      }
    }
  }
}

Integration with gatsby-image

You can use images coming from this plugin with gatsby-image. gatsby-image is a React component specially designed to work seamlessly with Gatsby’s GraphQL queries. It combines Gatsby’s native image processing capabilities with advanced image loading techniques to easily and completely optimize image loading for your sites.

To use this, you will first need to install and configure it and its dependencies.

npm install gatsby-image gatsby-transformer-sharp gatsby-plugin-sharp

Then add these plugins to gatsby-config.js:

plugins: [`gatsby-transformer-sharp`, `gatsby-plugin-sharp`]

You can then use the gatsby-image component:

import React from "react"
import { graphql } from "gatsby"
import Img from "gatsby-image"

export default ({ data }) => (
  <div>
    <h1>Hello gatsby-image</h1>
    <Img fluid={data.wcProducts.images[0].localFile.childImageSharp.fluid} alt={data.wcProducts.images[0].alt} />
  </div>
)

export const query = graphql`
  query allProducts {
     wcProducts (slug: {
        eq: "test-product"
      }) {
        id
        name
        images {
          alt
          localFile {
            childImageSharp {
              fluid {
                ...GatsbyImageSharpFluid
              }
            }
          }
        }
      }
  }
`

Some example queries for the fixed and fluid types are below.

Responsive Fluid

{
  wcProducts (slug: {
    eq: "test-product"
  }) {
    id
    name
    images {
      alt
      localFile {
        childImageSharp {
          fluid (maxWidth: 800, cropFocus: CENTER) {
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  }
}

Responsive Fixed

{
  wcProducts (slug: {
    eq: "test-product"
  }) {
    id
    name
    images {
      alt
      localFile {
        childImageSharp {
          fixed (width: 800, toFormat: JPG) {
            ...GatsbyImageSharpFixed
          }
        }
      }
    }
  }
}

Resize

{
  wcProducts (slug: {
    eq: "test-product"
  }) {
    id
    name
    images {
      alt
      localFile {
        childImageSharp {
          resize (width: 800, height: 600, cropFocus: CENTER, quality: 80) {
            src
          }
        }
      }
    }
  }
}

You can visit gatsby-image for more information, and to learn about the different types of queries.

Changelog

  • 0.17.3: Update gatsby-source-filesystem to resolve dependency warning
  • 0.17.1: Drop gatsby-source-filesystem version
  • 0.17.0: Revert changing to gatsby-core-utils; update gatsby-source-filesystem version
  • 0.16.1: Change gatsby-core-utils min version number
  • 0.16.0: Replace gatsby-source-filesystem with gatsby-core-utils to avoid some problems with package installation
  • 0.15.1: Wrap initialisation of WooCommerce REST API library in try / catch to reduce unhelpful errors.
  • 0.15.0: Fix issue with image download caching logic when using new versions of Gatsby
  • 0.14.0: Support for Product Attributes with terms.
  • 0.13.0: Support for Metadata fields and Misc data added
  • 0.12.0: Variable product data pulled in in parallel, verbose flag added. Improves build time for large number of products with variations.
  • 0.11.0: Add wordpress_parent_id field, to get around the parent field being overriden by the GraphQL node parent field. Additionally, added wordpress_parent & wordpress_children bidirectional links to the nodes themselves.
  • 0.10.0: Expanded API config options, including Basic Authentication as query string, and custom port, encoding, & axios config options.
  • 0.9.0: ACF image support, c/o 8ctopotamus. Test suite extension (node processing, without field mapping). Revert case insensitive field names - API request doesn’t care, but allows for fields with capitals; more freedom to the dev.
  • 0.8.1: Case insensitive field names & start of test suite c/o Siemah
  • 0.8.0: Add wpAPIPrefix option for custom WP REST API url prefix.
  • 0.7.0: Change to new library to access the WooCommerce REST API, since the old one is now obsolete. Change behaviour to pull in all resources of a given field name, when there are more resources than the value of the per_page option. Make ‘wc/v3’ default API version.
  • 0.6.2: Fix race condition when adding sharp images to products
  • 0.6.1: Add Gatsby Image support (localFile field) to product variations images.
  • 0.6.0: Properly support product variations, accessible through the product_variations field on products.
  • 0.5.0: Added grouped_products_nodes field to products. Points to the node of each grouped product (or an empty array if not a grouped product). Grouped product nodes found under grouped_products_nodes rather than grouped_products to allow for backwards compatibility.
  • 0.4.0: Also map related products as product nodes, rather than just an array of IDs
  • 0.3.5: Gatsby Image related documentation c/o Travis Reynolds
  • 0.3.4: Mapping products & tags to each other
  • 0.3.3: Fixing issues related to product - category mapping, API version. (Thank you Travis Reynolds). Product categories IDs can now also be accessed with wordpress_id when no category nodes are pulled in. This is to keep access consistent, whether or not categories are used. Previously, without the ‘products/categories’ field, product category ID was accessed as product.categories.id (an integer), while with the ‘products/categories’ field, it was product.categories.wordpress_id (since categories.id is now the node ID - a string).
  • 0.3.2: Mapping products & categories to each other
  • 0.3.0: Associated products & product categories with local file images downloaded during the build process to allow use of image transform plugins.
© 2023 Gatsby, Inc.