What is gatsby-source-wordpress?
The gatsby-source-wordpress plugin is an official Gatsby plugin that sources data from WordPress sites in a scalable and efficient way using WPGraphQL. Unlike older approaches that relied on the WordPress REST API, this plugin leverages WPGraphQL to merge the WordPress schema and data directly with Gatsby's GraphQL data layer, creating a unified development experience.
This plugin works by connecting to a WordPress site that has the WPGraphQL plugin installed, fetching all available content types including posts, pages, custom post types, and custom taxonomies, then making this data available throughout your Gatsby site for querying and rendering. The result is a static site that pulls its content dynamically from WordPress during the build process, offering the best of both worlds: WordPress's content management capabilities and Gatsby's performance benefits.
Why Choose gatsby-source-wordpress?
The gatsby-source-wordpress approach delivers significant advantages over traditional WordPress hosting. Performance gains come from serving pre-built static files rather than dynamically generating pages on each request. Security improves by removing the database and WordPress PHP execution from your public-facing infrastructure. Developer experience benefits from modern JavaScript tooling, component-based architecture, and the full Gatsby ecosystem. For teams already comfortable with WordPress as a content management interface, this architecture provides a migration path to a modern frontend stack without changing the editorial workflow.
The plugin automatically handles incremental builds when possible, reducing build times for sites with large content libraries by only sourcing content that has changed since the last build. This efficiency makes the architecture viable for content-heavy sites that would otherwise face prohibitively long build times with naive sourcing approaches.
If you're exploring how to combine Gatsby with WordPress data, our guide on Creating a Gatsby Site with WordPress Data provides additional practical implementation details.
The plugin provides comprehensive data sourcing for your entire WordPress content structure
Posts and Pages
Fetch content, excerpts, featured images, and metadata from all standard WordPress content types
Custom Post Types
Automatically detect and source custom post types defined in your WordPress installation
Taxonomies
Access categories, tags, and custom taxonomies for robust content organization
Media Files
Source images and files from the WordPress media library with optimization support
Prerequisites and Installation
Before installing gatsby-source-wordpress, ensure your development environment meets the basic requirements. You'll need Node.js installed (version 18 or later is recommended), npm or yarn for package management, and a WordPress site with WPGraphQL activated as the data source.
Setting Up WPGraphQL on WordPress
The WordPress side of the equation requires the WPGraphQL plugin, which creates a GraphQL API endpoint for your WordPress content. Install WPGraphQL through the WordPress plugin directory or via Composer if you prefer managing plugins that way. Once activated, navigate to GraphQL in your WordPress admin to verify the endpoint is working and explore your site's schema through the built-in GraphiQL IDE.
// Install via Composer (optional alternative)
composer require wp-graphql/wp-graphql
// After activation, access the GraphQL endpoint at:
// https://your-wordpress-site.com/graphql
WPGraphQL exposes your WordPress content through a well-structured GraphQL schema that gatsby-source-wordpress can consume. The plugin supports Advanced Custom Fields through the WPGraphQL for ACF extension, allowing you to source custom field data alongside standard WordPress content. This extensibility makes it possible to model complex content structures while maintaining clean data sourcing.
To verify your WPGraphQL installation is working correctly, access the GraphiQL IDE at your WordPress admin's GraphQL section. You should be able to run queries like { posts { nodes { title } } } and receive valid responses containing your WordPress content. If the schema introspection fails or returns errors, check that permalinks are properly configured and that the WPGraphQL plugin is fully activated.
For teams looking to modernize their web development workflow while maintaining familiar content management tools, combining WordPress with a modern frontend framework like Gatsby represents a strategic approach to web development services.
1# Install the gatsby-source-wordpress plugin2npm install gatsby-source-wordpress3 4# Verify installation5npm list gatsby-source-wordpress6 7# The plugin supports TypeScript configurations8# Add to your gatsby-config.js file9# See configuration examples belowConfiguration and Connection
Proper configuration is essential for establishing a reliable connection between Gatsby and your WordPress site. The gatsby-source-wordpress plugin offers extensive configuration options to control what content is sourced, how it's cached, and how the build process handles various scenarios.
Basic Configuration
The foundational configuration requires specifying your WordPress site's GraphQL endpoint URL. This URL typically follows the pattern of your WordPress site followed by /graphql, such as https://your-wordpress-site.com/graphql. The plugin uses this endpoint to introspect your WordPress schema and begin sourcing content.
// gatsby-config.js
module.exports = {
plugins: [
{
resolve: `gatsby-source-wordpress`,
options: {
url: `https://your-wordpress-site.com/graphql`,
},
},
],
}
Beyond the basic URL, you can configure which content types to include or exclude, set up authentication for private WordPress sites, configure caching behavior, and control how the plugin handles various WordPress-specific features. The plugin supports Basic Authentication for development environments and can integrate with authentication plugins for production deployments where the WordPress site needs protection.
Advanced Configuration Options
For larger WordPress sites, configuration options become crucial for managing build performance and data sourcing behavior. You can limit the number of items fetched per batch, configure retry behavior for failed requests, and set up webhooks to trigger incremental builds when content changes in WordPress.
{
resolve: `gatsby-source-wordpress`,
options: {
url: `https://your-wordpress-site.com/graphql`,
// Limit items fetched per batch for memory management
html: {
useGatsbyImage: true,
imageProcessingOptions: {
stripMetadata: true,
defaultImageProps: {
alt: "",
layout: "constrained",
},
},
},
// Authentication for private WordPress sites
auth: {
wpcom_user: process.env.WORDPRESS_USER,
app_password: process.env.WORDPRESS_APP_PASSWORD,
},
// Exclude specific content types from sourcing
type: {
Post: {
limit: process.env.NODE_ENV === "development" ? 50 : 500,
},
},
},
}
The html.useGatsbyImage option enables automatic image optimization for images embedded in your WordPress content, creating responsive, optimized versions through Gatsby's image processing pipeline. The plugin also supports configuring how it handles preview content, allowing your editorial team to preview changes before publishing.
Fetching Data with GraphQL
Once configured, gatsby-source-wordpress makes your WordPress content available through Gatsby's unified GraphQL data layer. This integration means you can write queries that combine WordPress data with data from other sources, creating rich, interconnected content experiences. The GraphQL schema mirrors your WordPress structure, with nodes for each content type and connections between related content.
Querying Posts and Pages
Standard queries retrieve posts with their associated data including title, content, excerpt, date, author, categories, tags, and featured image. The plugin creates connection types that allow you to traverse relationships between content, such as finding all posts in a specific category or all pages by a particular author.
Working with Custom Post Types and Taxonomies
WordPress sites often extend beyond the default posts and pages with custom post types for portfolios, products, testimonials, or any specialized content type. The gatsby-source-wordpress plugin automatically detects these custom post types and creates corresponding GraphQL query types following the wp{PostTypeName} naming convention. Custom taxonomies function similarly, with queries like allWpPortfolioCategory for taxonomy-based filtering and grouping.
# Querying custom post types
query PortfolioItems {
allWpPortfolio(
sort: { date: DESC }
filter: { featured: { eq: true } }
) {
nodes {
title
slug
excerpt
portfolioFields {
clientName
projectUrl
completionDate
technologiesUsed
}
featuredImage {
node {
altText
localFile {
childImageSharp {
gatsbyImageData(
width: 1200
placeholder: BLURRED
formats: [AUTO, WEBP, AVIF]
)
}
}
}
}
}
}
}
# Querying custom taxonomies
query PortfolioCategories {
allWpPortfolioCategory {
nodes {
name
slug
description
posts {
nodes {
title
slug
}
}
}
}
}
This automatic schema generation means your Gatsby queries can adapt as your WordPress content model evolves. Adding a new custom post type in WordPress automatically becomes available for querying in Gatsby without requiring configuration changes, providing flexibility for content strategy adjustments over time.
Understanding these GraphQL patterns is essential for effective web development when building headless WordPress architectures.
1query WordPressPosts {2 allWpPost(sort: { date: DESC }, limit: 10) {3 nodes {4 title5 excerpt6 slug7 date(formatString: "MMMM DD, YYYY")8 content9 author {10 node {11 name12 avatar {13 url14 }15 }16 }17 featuredImage {18 node {19 altText20 localFile {21 childImageSharp {22 gatsbyImageData(width: 800, placeholder: BLURRED)23 }24 }25 }26 }27 categories {28 nodes {29 name30 slug31 }32 }33 tags {34 nodes {35 name36 slug37 }38 }39 }40 }41 42 # Query pages separately43 allWpPage {44 nodes {45 title46 slug47 template {48 templateName49 }50 }51 }52}Creating Pages from WordPress Content
A common pattern in Gatsby + WordPress sites is dynamically generating pages for each post, page, or custom post type item. The gatsby-node.js file provides the hook for creating these pages programmatically, using the sourced WordPress data to generate paths and associate templates.
Dynamic Page Generation
The createPages API in gatsby-node.js queries your WordPress data and iterates through results to create individual pages. Each page receives context containing the data needed to render it, and a path that determines its URL on your site. This approach enables you to build entire websites where the content lives in WordPress but the presentation is fully controlled through Gatsby templates.
// gatsby-node.js
const path = require('path')
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
// Query all posts
const result = await graphql(`
{
allWpPost {
nodes {
slug
id
}
}
# Query custom post types
allWpPortfolio {
nodes {
slug
id
}
}
}
`)
if (result.errors) {
result.errors.forEach(error => console.error(error))
return
}
const postTemplate = path.resolve('./src/templates/post.js')
const portfolioTemplate = path.resolve('./src/templates/portfolio.js')
// Create blog posts
result.data.allWpPost.nodes.forEach(node => {
createPage({
path: `/blog/${node.slug}`,
component: postTemplate,
context: {
id: node.id,
},
})
})
// Create portfolio pages
result.data.allWpPortfolio.nodes.forEach(node => {
createPage({
path: `/portfolio/${node.slug}`,
component: portfolioTemplate,
context: {
id: node.id,
},
})
})
}
Template Development
Templates receive the WordPress content through their GraphQL query and render it using React components. The template files live in your project's source directory and can use any of Gatsby's features including layout components, context providers, and image optimization.
// src/templates/post.js
export const query = graphql`
query($id: String!) {
wpPost(id: { eq: $id }) {
title
date(formatString: "MMMM DD, YYYY")
content
featuredImage {
node {
altText
localFile {
childImageSharp {
gatsbyImageData(width: 1200, placeholder: BLURRED)
}
}
}
}
author {
node {
name
description
}
}
}
}
`
const PostTemplate = ({ data }) => {
const { wpPost: post } = data
return (
<Layout>
<article>
<h1>{post.title}</h1>
<time>{post.date}</time>
{post.featuredImage && (
<GatsbyImage
image={post.featuredImage.node.localFile.childImageSharp.gatsbyImageData}
alt={post.featuredImage.node.altText}
/>
)}
<div dangerouslySetInnerHTML={{ __html: post.content }} />
</article>
</Layout>
)
export default PostTemplate
The context.id passed to each page becomes available in the template's GraphQL query through the $id variable, allowing you to fetch the specific content for that page. This pattern scales efficiently even for sites with thousands of pages, as Gatsby's build system handles the creation process in batches.
Image Handling and Optimization
One of Gatsby's standout features is its image optimization pipeline, and the gatsby-source-wordpress plugin integrates fully with this capability. Images uploaded to WordPress are sourced along with other content and processed through Sharp to create multiple responsive sizes, blur-up placeholders, and webp variants. This optimization significantly improves page load times and core web vitals scores.
Configuring Image Processing
The plugin's html option with useGatsbyImage enabled processes images embedded in WordPress content, transforming standard img tags into optimized Gatsby Image components. This processing happens at build time, so the resulting static site serves pre-built responsive images rather than requiring browser-side processing.
{
resolve: `gatsby-source-wordpress`,
options: {
url: `https://your-wordpress-site.com/graphql`,
html: {
// Enable Gatsby Image processing for embedded content
useGatsbyImage: true,
// Configure image processing options
imageProcessingOptions: {
// Remove EXIF and other metadata
stripMetadata: true,
// Default props for processed images
defaultImageProps: {
alt: "",
layout: "constrained",
formats: ["auto", "webp", "avif"],
},
},
},
// Handle responsive images from media library
presets: {
default: {
quality: 90,
withWebp: true,
withAvif: true,
},
},
},
}
For featured images and other media library items, query them through the GraphQL schema and use childImageSharp or the gatsbyImageData field to access processed versions. The gatsbyImageData field accepts numerous parameters for controlling size, aspect ratio, placeholder style, and format (webp, avif), providing fine-grained control over how images appear throughout your site.
query FeaturedImageExample {
wpPost(id: { eq: "some-id" }) {
featuredImage {
node {
altText
mediaDetails {
width
height
}
localFile {
childImageSharp {
gatsbyImageData(
layout: CONSTRAINED
width: 800
placeholder: BLURRED
formats: [AUTO, WEBP, AVIF]
outputPixelDensities: [1, 2]
)
}
}
}
}
}
}
This integration means you can deliver optimal image experiences for your visitors while managing all images through the familiar WordPress media library interface your content team already uses. Fast, optimized images contribute to better SEO performance and user engagement.
Best Practices for Production
Deploying a Gatsby + WordPress site to production requires attention to several operational considerations that ensure reliability, performance, and maintainability over time.
Incremental Builds
Build times increase with content volume, so implementing incremental builds through webhooks keeps your deployment pipeline efficient. Configure webhooks in WordPress to trigger Gatsby builds when content changes. This approach ensures your static site stays current without requiring manual rebuilds.
// gatsby-config.js - Webhook configuration for content updates
exports.createWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
plugins: [
// Build plugin that responds to WP webhooks
],
})
}
// In your WordPress admin, set up webhooks pointing to:
// Your CI/CD webhook trigger URL
// Trigger on: publish_post, publish_page, save_post (custom post types)
Environment-Specific Configuration
Environment-specific configuration for development, staging, and production WordPress instances allows team members to work with local or development content while the production site sources from your live WordPress installation.
// gatsby-config.js
const WORDPRESS_URL = process.env.WORDPRESS_URL || 'https://dev-wordpress.com'
module.exports = {
plugins: [
{
resolve: `gatsby-source-wordpress`,
options: {
url: `${WORDPRESS_URL}/graphql`,
// Development-specific settings
...(process.env.NODE_ENV === 'development' && {
verbose: true,
html: {
useGatsbyImage: false, // Skip for faster dev builds
},
}),
},
},
],
}
Caching Strategies
Caching strategies improve build performance by storing sourced data between builds. The plugin uses file-based caching by default, with options for customizing cache location and behavior. For CI/CD environments, ensure the cache directory persists between pipeline runs to maintain incremental build benefits.
Monitoring
Monitoring your build process helps identify issues before they impact deployment. The plugin provides detailed logging during sourcing that can reveal configuration problems, GraphQL errors, or content issues that need attention. Integrate this logging with your CI/CD system's output to ensure build failures are caught and addressed promptly.
// Enable verbose logging for troubleshooting
exports.onPluginInit = ({ reporter }) => {
if (process.env.GATSBY_VERBOSE_LOGGING) {
reporter.info('Verbose logging enabled for gatsby-source-wordpress')
}
}
Following these practices ensures your Gatsby + WordPress architecture remains performant and maintainable as your content library grows. For organizations exploring modern digital solutions that combine traditional CMS strengths with cutting-edge frontend technologies, headless architecture represents an effective path forward.
Frequently Asked Questions
Sources
- Gatsby: Sourcing from WordPress - Official Gatsby documentation providing comprehensive guidance on using gatsby-source-wordpress with WPGraphQL
- Gatsby: WordPress Source Plugin Tutorial - Step-by-step tutorial for creating sites with WordPress data sourcing
- Kinsta: Building websites with Gatsby and WordPress - Detailed tutorial covering Gatsby installation, WordPress integration, and advanced migration tasks
- NPM: gatsby-source-wordpress - Package details, installation, and version information