To follow along

https://ebeldev.github.io/headlesswordpress-slides/

the goal for today

- Use Wordpress as a backend service api

& use new stack to deliver the front-end

Front-end stack for today = ReactJS and GraphQL

Étienne Bélanger

  • Self-taugh web developper
  • WordPress lover for more then 10 years
  • Work @ DistrictWeb as full-stack developer
  • Contact
    • etienne@etiennebelanger.com
    • belangeretienne
    • @ebeldev
    • @ebeldev

The web has changed a lot

and so did WordPress

Advantages of Headless CMS

separate content and presentation

generate unique user experiences

make your content available to mobile apps, kiosk, VR experiences, and other mediums

Rest Api

/wp-json/wp/v2/

Rest Api

/wp-json/wp/v2/

/posts

/media/"id"

/users/"id"

/categories/"id"

Rest Api

desavantages

Over-fetching = a client downloads more information than is actually needed

Under-fetching = a specific endpoint doesn’t provide enough of the required information

Maintainability and Scalability having too many endpoints

Open-sourced by Facebook in 2015

A query language for your API

GraphQL

Type of operations you can do on your api

Query get your data

Mutation modify your data

Subscription subscribe to action

GraphQL has two parts

Server

Responsible for the SCHEMA of your API and resolvers of the data


type Query {
 posts: [Post]
}

type Post {
 title: String
 content: String
 author: Author
}

type Author {
 name: String
 avatar: String 
 posts: [Post]
}
Client

Responsible for making the query to the server


								query {
								 posts {
								  title
								  author {
								   name
								   avatar
								  }
								 }
								}
								


{"data": {
  "posts": {
   "edges": [{
     "node": {
      "title": "Hello World",
      "author": {
	   name: "My super name",
       avatar: "http://www.imagesource.com/authoravatar.jpg"
	  }
     }
   }]
  }
}}
								

GraphQL options

Server

Custom

PrismaFramework for self-hosted GraphQL server

WordExpressFramework to help develop Wordpress applications (server + client)

wp-graphqlWordPress pluginhttps://github.com/wp-graphql/wp-graphql

Client

RelayFrom Facebook, for more advance developpers

Apollo-clientApollo-boost = no setup, cache, manage local and server data

WordPress Setup

WordPress will serve as the backend system on which GraphQL will be hocked on

Install wp-graphql plugin

Extending Wp-Graphql plugin in your theme functions.php


use WPGraphQL\Types;

function wcgql_add_custom_fields_to_graphql ($fields) {
  $fields['custom'] = [
    'type' 			=> Types::String(),
	'description'	=> __( 'The date the film was released', 'wcmtl-graphql' ),
	'resolve'		=> function ( \WP_Post $post ) {
	  // Get your data
	  $customField = get_post_meta( $post->ID, 'custom_field_name', true );
	  // make any modification on your data
	
	  // Return your data
	  return $customField;
	},
  ];

  return $fields;
}

add_filter( 'graphql_post_fields', 'wcgql_add_custom_fields_to_graphql', 10, 1 );

ReactJS Setup

NodeJS

In your command line

npx create-react-app nameofyourproject

cd nameofyourproject

  • npm install apollo-boost react-apollo graphql —-save
    • apollo-boost: Apollo-Client
    • react-apollo: View layer integration in react
    • graphql: Parses GraphQL queries

npm install react-router-dom —-save

npm start

localhost:3000

Apollo-Boost Client Setup Create a Provider


	import React, { Component } from 'react';
	import ApolloClient from "apollo-boost";
	import { ApolloProvider } from "react-apollo";

	const client = new ApolloClient({
	uri: "http://localhost/wordcamp2018/graphql"
	});

	class App extends Component {
	render() {
	return (
	
		

Welcome to Headless WordPress

); } } export default App;

Apollo-Boost Client Setup Create a client


	import React, { Component } from 'react';
	import ApolloClient from "apollo-boost";
	import { ApolloProvider } from "react-apollo";

	const client = new ApolloClient({
	uri: "http://localhost/wordcamp2018/graphql"
	});

	class App extends Component {
	render() {
	return (
	
		

Welcome to Headless WordPress

); } } export default App;

Apollo-Boost Client Setup Wrap your provider


		import React, { Component } from 'react';
		import ApolloClient from "apollo-boost";
		import { ApolloProvider } from "react-apollo";
	
		const client = new ApolloClient({
		uri: "http://localhost/wordcamp2018/graphql"
		});
	
		class App extends Component {
		render() {
		return (
		
			

Welcome to Headless WordPress

); } } export default App;

Apollo-Boost Client in Component Import Libraries


		import React, { Fragment } from 'react';
		import { Query } from 'react-apollo';
		import gql from 'graphql-tag';
		

Apollo-Boost Client in Component Create your query


		import React, { Fragment } from 'react';
		import { Query } from 'react-apollo';
		import gql from 'graphql-tag';
		
		const GET_POSTS = gql`
		 query GET_POSTS {
		  posts {
		   edges {
		    node {
		     id
		     title
		     date
		    }
		   }
		  }
		 }
		`;
									

Apollo-Boost Client in Component Output the data


		export default function Posts() {
		 return (
		  
		   {({ data, loading, error }) => {
		    if (loading) return 

A spinner

; if (error) return

ERROR

; return ( {data.posts && data.posts.posts && data.posts.posts.map(post => ( console.log(post) ))} ); }}
); };

See the slides

https://ebeldev.github.io/headlesswordpress-slides/

Extra

GraphQL + Wordpress with Jason Bahl https://www.youtube.com/watch?v=tYXlHb2eyQw

GraphQL + Wordpress Learning site https://edwincromley.gitbooks.io/wp-graphql/content/

Learn GraphQL howtographql.com

Apollo GraphQL apollographql.com