Gatsby is great for personal or static site, WordPress is great for blogging. If you have a WordPress blog and want to include the recent post on your Gatsby static site or personal website like below
You can follow these simple steps
Adding WordPress recent blogs to your Gatsby Site
- Add WPGatsby and WPGraphQL Plugins to your WordPress.
- Add the
gatsby-source-wordpress
package to your gatsby code usingyarn add gatsby-source-wordpress
ornpm install gatsby-source-wordpress
- Edit your
gatsby-config.js
file and add the plugin like below example. Use your web URL with/graphql
at the end.
{
resolve: `gatsby-source-wordpress`,
options: {
url: `https://www.regardingtech.com/graphql`,
},
},
- Gatsby Page Query to fetch the latest post from WordPress using GraphQL. Here we are fetching the top six latest posts from the blog
export const pageQuery = graphql`
query {
allWpPost(limit: 6, sort: {fields: [date], order: DESC}) {
nodes {
title
link
excerpt
featuredImage {
node {
link
altText
}
}
}
}
}
- All the nodes from above query will be fetched and made available in component props as
data
which can be used to design your page.
export default function Home({ data }) {
return (
<Layout>
<Seo title="Shishir Singh's Blog Posts" />
<div id="blog" className="container section blog">
<div className="section-heading has-text-centered mb-6">
<h3 className="title is-2">Blog</h3>
<h4 className="subtitle is-5">Recent Posts</h4>
</div>
{data.allWpPost.nodes.map(node => (
<article key={node?.link} className="media">
<figure className="media-left">
<p className="image is-64x64">
<img alt={node.featuredImage?.node?.altText} src={node.featuredImage?.node?.link} />
</p>
</figure>
<div className="media-content">
<div className="content">
<a target="_blank" rel="noopener noreferrer" href={`https://www.regardingtech.com${node.link}`}>
<strong>{node.title}</strong>
</a>
<br />
<div dangerouslySetInnerHTML={{ __html: node.excerpt }} />
</div>
</div>
</article>
))}
</div>
</Layout>
)
}
In your browser, open
http://localhost:8000 to see your site, and open http://localhost:8000/___graphql
so that you can create your GraphQL queries.