All Projects → MaedahBatool → gatsby-with-wordpress

MaedahBatool / gatsby-with-wordpress

Licence: MIT license
Gatsby integration with WordPress

Programming Languages

javascript
184084 projects - #8 most used programming language
CSS
56736 projects

Projects that are alternatives of or similar to gatsby-with-wordpress

FizzBuzz-Hacktoberfest-2021
🎃 Submit creative FizzBuzz solutions in any language you want! Open for beginners !
Stars: ✭ 17 (-45.16%)
Mutual labels:  hacktoberfest-accepted
Nallagram
Nallagram is an open source social networking platform where users can share their views on various topics and interact among people in which they create, share, and/or exchange information and ideas in virtual communities and networks.
Stars: ✭ 30 (-3.23%)
Mutual labels:  hacktoberfest-accepted
Web-Development
Created this new Repository for Open Source Contribution for Beginners
Stars: ✭ 25 (-19.35%)
Mutual labels:  hacktoberfest-accepted
conteudos-tech
- Esse repositório foi criado por mim, Fernanda Souza, com o intuito de divulgar ferramentas gratuitas que possam auxiliar pessoas em seus estudos.
Stars: ✭ 62 (+100%)
Mutual labels:  hacktoberfest-accepted
doto-client
Track your progress and multiply efficiency
Stars: ✭ 41 (+32.26%)
Mutual labels:  hacktoberfest-accepted
Data-Structures-And-Algorithms
Important data structure and algorithms codes and concept's open-source repository.
Stars: ✭ 48 (+54.84%)
Mutual labels:  hacktoberfest-accepted
E-Learning-freesite
This site is mainly design for those student who don't know how to start their journey in the field of programming
Stars: ✭ 57 (+83.87%)
Mutual labels:  hacktoberfest-accepted
Learn-To-Use-Github
Wanna Learn How to use github ? come on in
Stars: ✭ 68 (+119.35%)
Mutual labels:  hacktoberfest-accepted
VariantRetriever
VariantRetriever is a minimalist package for feature flagging
Stars: ✭ 23 (-25.81%)
Mutual labels:  hacktoberfest-accepted
Competitive Programming
Programming👨‍💻 Questions on BinarySearch💻, LeetCode💻, CodeChef💻, Codeforces💻,DSA 450
Stars: ✭ 188 (+506.45%)
Mutual labels:  hacktoberfest-accepted
projecthactoberfest
hactoberfest 2022
Stars: ✭ 32 (+3.23%)
Mutual labels:  hacktoberfest-accepted
General-Purpose-Scripts
A repository containing several general purpose Python scripts to automate daily and common tasks.
Stars: ✭ 47 (+51.61%)
Mutual labels:  hacktoberfest-accepted
CodeSignal-Practice Solutions
No description or website provided.
Stars: ✭ 28 (-9.68%)
Mutual labels:  hacktoberfest-accepted
auto-grader
Automatically grades answer sheets
Stars: ✭ 17 (-45.16%)
Mutual labels:  hacktoberfest-accepted
Kuberam
Kuberam is built on jetpack compose + Auth0 during Hashnode Hackathon.
Stars: ✭ 33 (+6.45%)
Mutual labels:  hacktoberfest-accepted
locus-android
An Awesome Kotlin Location library to retrieve location merely in 3 lines of code
Stars: ✭ 280 (+803.23%)
Mutual labels:  hacktoberfest-accepted
Web-Development
Web Development- GameofSource
Stars: ✭ 14 (-54.84%)
Mutual labels:  hacktoberfest-accepted
Bundli-Frontend
Bundli-Frontend 🚩 is a repo which contains 🚀different code of full stack Development 👨‍💻🚀
Stars: ✭ 133 (+329.03%)
Mutual labels:  hacktoberfest-accepted
formica
A discord bot that collects and analyzes form data
Stars: ✭ 20 (-35.48%)
Mutual labels:  hacktoberfest-accepted
Hacktoberfest-2021
This is A Hacktoberfest 2021 Python Repository
Stars: ✭ 13 (-58.06%)
Mutual labels:  hacktoberfest-accepted


Gatsby & WordPress Integration


Building static sites with React.js using Gatsby provides an easy to deploy setup, blazing fast speed, and smooth developer experience. JAMstack (JavaScript APIs Markup) is awesome and I am going to show you why it has become such a popular tool by demonstrating how you can leverage Gatsby to supercharge your next WordPress site.

First we are going to configure a basic Gatsby project setup. And then we'll use it to fetch data from our WordPress site.

Integrating Gatsby.js with WordPress

Step #0: Don't have a Gatsby site setup? Read this. (CLICK TO EXPAND!)

If this is your first time with Gatsby.js, all you need to do is follow these steps mentioned below. These will help you set up a basic Gatsby project.

  • Install the Gatsby CLI by typing the following command in your terminal
npm install -g gatsby-cli
  • Next, create a new Gatsby.js site through the following.
gatsby new site-name
  • To access your site folder contents type the following.
cd site-name
  • Finally, start the development server to begin building your Gatsby.js site.
gatsby develop

#1: Install gatsby-source-wordpress Plugin

If you have a WordPress site and you want to have its front-end built with Gatsby.js all you need to do is pull the existing data into your static Gatsby site. You can do that with the gatsby-source-wordpress plugin.

Inside your terminal type the following to install this plugin.

npm install gatsby-source-wordpress

#2: Configuring the plugin

Inside your gatsby-config.js file, add the configuration options which includes your WordPress site’s baseUrl, protocol, whether it’s hosted on WordPress.com or self-hosted i.e., hostingWPCOM, and whether it uses the Advanced Custom Fields (ACF) plugin or not useACF Also, we are going to mention all the includedRoutes which tells what data do we exactly want to fetch.

Inside your gatsby-config.js file, the configuration options looks like this:

module.exports = {
  // ...
  plugins: [
    // ...
    {
    	resolve: `gatsby-source-wordpress`,
    	options: {
    		// Your WordPress source.
    		baseUrl: `demo.wp-api.org`,
    		protocol: `https`,
    		// Only fetches posts, tags and categories from the baseUrl.
    		includedRoutes: ['**/posts', '**/tags', '**/categories'],
    		// Not using ACF so putting it off.
    		useACF: false
    	}
    },
  ],
}

#3: Using the Fetched WordPress Data

Once your Gatsby site is fetching data from your WordPress source URL, next you'll create your site pages. This is done by implementing the createPages API in the gatsby-node.js.

This makes your fetched data available to be queried with GraphQL. At build time, the gatsby-source-wordpress plugin fetches your data, and use it to ”automatically infer a GraphQL schema” which you can query against.

Here's the code of the gatsby-node.js file which iterates the WordPress post data.

/**
 * Implement Gatsby's Node APIs in this file.
 *
 * See: https://www.gatsbyjs.org/docs/node-apis/
 */

const path = require(`path`);
const slash = require(`slash`);

/**
 * Implement the Gatsby API “createPages”. This is
 * called after the Gatsby bootstrap is finished so you have
 * access to any information necessary to programmatically
 * create pages.
 * Will create pages for WordPress pages (route : /{slug})
 * Will create pages for WordPress posts (route : /post/{slug})
 */
exports.createPages = async ({ graphql, actions }) => {
	const { createPage } = actions;

	/*
	 * The “graphql” function allows us to run arbitrary
	 * queries against the local Gatsby GraphQL schema. Think of
     * it like the site has a built-in database constructed
	 * from the fetched data that you can run queries against.
	 */
	const result = await graphql(`
		{
			allWordpressPost {
				edges {
					node {
						id
						slug
						status
						template
						format
					}
				}
			}
		}
	`);

	// Check for any errors.
	if (result.errors) {
		throw new Error(result.errors);
	}

	// Access query results via object destructuring.
	const { allWordpressPost } = result.data;
	const postTemplate = path.resolve(`./src/templates/post.js`);

	/*
	 * We want to create a detailed page for each
	 * post node. We'll just use the WordPress Slug for the slug.
	 * The Post ID is prefixed with 'POST_'
	 */
	allWordpressPost.edges.forEach(edge => {
		createPage({
			path: `/${edge.node.slug}/`,
			component: slash(postTemplate),
			context: {
				id: edge.node.id
			}
		});
	});
};

#4: Create a post.js Template

Then, create a folder for templates and add files for posts, pages, layouts, etc. For now, I am creating a post.js file since I am fetching the posts from my WordPress site.

Here's the code:

import { graphql } from 'gatsby';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Layout from '../layouts';

class PostTemplate extends Component {
	render() {
		const post = this.props.data.wordpressPost;

		return (
			<Layout>
				<h1 dangerouslySetInnerHTML={{ __html: post.title }} />
				<div dangerouslySetInnerHTML={{ __html: post.content }} />
			</Layout>
		);
	}
}

PostTemplate.propTypes = {
	data: PropTypes.object.isRequired,
	edges: PropTypes.array
};

export default PostTemplate;

export const pageQuery = graphql`
	query($id: String!) {
		wordpressPost(id: { eq: $id }) {
			title
			content
		}
	}
`;

#5: Final Result

To start the development server to view the final result type the following command.

npm start

You get the link from where you can access the site locally along with other details like no. of posts, categories and tags that are being fetched.

👋 Follow @MaedahBatool on Twitter

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].