Using WordPress As A GraphQL Backend
Tags: wordpress, webdev, graphql, programming
Published: 2022-08-08 01:48:03

> This article was first posted on [devjavu.space](https://devjavu.space/post/using-wordpress-as-a-graphql-backend/)

[WordPress](https://www.wordpress.com/) has been the go-to solution for building websites for the longest of time. From simple static landing pages to blogs and e-commerce websites. However, one major setback it has is scalability & reusability. Say you wanted to use your content on other clients or services, a mobile application, for example, it’s mostly a pain to achieve because of the monolith structure of WordPress.

WordPress, however, added the [WordPress REST API](https://developer.wordpress.org/rest-api/) that allows developers to access and use data outside of WordPress. The only problem with this is, the data from REST API is bloated, and contains a lot of unnecessary things. This is why we’re choosing to use [GraphQL](http://graphql.org/).

We’ll be working with an offline version of WordPress, although you can easily get a full WordPress installation when you purchase a hosting plan from a [hosting provider](http://www.hostinger.com/). You would however only need this when you have to host your WordPress backend.

I’ll walk you through how to set it up locally.

---

## Getting Started

Requirement:

- LAMP Setup
- Basic knowledge of [WordPress](https://wordpress.com/)
- Basic knowledge of [Graphql](http://graphql.org/learn/)

Download the latest version of WordPress here. This will download a .zip file to your local machine.

{% embed https://wordpress.org/download/#download-install %}

Unzipping the file should give you a WordPress folder that contains all the essential files needed by WordPress. Open up your Terminal or Command Line Prompt and work your way into the WordPress folder.

```bash
cd ~/Downloads/wordpress
```

Once you’re in the **WordPress** folder, You’ll need to use the PHP interactive shell to start a simple server.

Make sure you’re in the root directory that contains the `index.php` file, from there run:

```bash
php -S localhost:8000
```

This should start a server on port 8000. Navigate to `localhost:8000` in your browser. You should see the WordPress onboarding page. Select a language and click “Continue”.

![wordpress graphql](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pfujckkubi3plrctj43r.png)

You should be presented with a prompt right after. Here, you’ll be asked to provide some database information including; name, username, password, table prefix, and host. This enables WordPress to generate all the required tables for a complete installation.

![wordpress graphql](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7gllsbjg33m5mxfl6wk5.png)

Before you continue with this step, it is important that you have the correct installation of PHP and MySQL on your PC. Here’s a guide I wrote, it should help you set up your PC for PHP development.

{% embed https://devjavu.space/post/the-hitchhiker-s-guide-to-laravel-setup/ %}  

Once you’re sure you have them set up correctly done, fill in the details for your WP database.

![wordpress graphql](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3cf9mj3jg9xs8mjoihtd.png)

- **Database Name**: The name of an existing MySQL database (be sure to create it first).
- The Username field is the username of any user that has access to your MySQL Database (usually “root”).
- **Password**: This should be the password of the MySQL user when setting up, if you didn’t set a password, you can leave this field blank.
- **Database Host**: Since we’re working on our local machine, this would be localhost. WP automatically sets the value, so leave it as is.
- **Table Prefix**: This prefix should be unique if you intend to run another WP installation locally. I will, however, leave this. 


If everything was done correctly you should see the next screen telling you that WordPress can now communicate with your database:

![WordPress GraphQL](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kr25dd9on2o2q7h83c9k.png)

Fill in the required information and click install WordPress.

https://miro.medium.com/max/2080/1*eodnBArlu59cHP7Yyl02zA.png

It should only take a few seconds for your installation to complete.

![wordpress graphql](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6rvo0kgexmhezcfv8bes.png)

Great job! Now we have WordPress installed locally. Login with the details into your admin dashboard.

## Installing WPGraphQL
Once logged in, head over to the Plugins option and select “Add Plugin”.  

![wordpress graphql](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4nq52lexrq3h5t2lbw3l.png)

Search for “graphql” and install the [WPGraphQL](http://wpgraphql.com/) plugin. Once installed, click on “Activate” to enable to Plugin. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s6w9r01br4r37sqn9ii3.png)
You should now see a new menu option called “GraphQL” on the left.

![wordpress graphql](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9lsumc8f8vbranm6i3e1.png)
Hover on this menu option and select “Settings”, this should take you to the WpGraphQL setting page. On the settings page, you’ll be provided with the option to change the GraphQL endpoint, this determines where you’ll make queries and mutations to.

![wordpress graphql](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xak10i3mezgjxl9xpgus.png)
 

The default value is `/graphql` feel free to leave it this way, only change it if you want something different. For now, we’ll leave other settings as is.  

> _Note: Enable the debug mode if you want more information about GraphQL errors, however, always disable this when you deploy to production:_

![wordpress graphql](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5du1wlnvbeo1lelpv7ps.png)

---

WordPress data (posts) can now be accessed using GraphQL queries. You can test out your GraphQL backend with any HTTP client like [Postman](https://www.postman.com/) or [Insomnia](https://insomnia.rest/). However, If you do not have either of these, the WPGraphQL plugin comes with an [IDE](https://www.apollographql.com/docs/apollo-server/v1/graphiql/) preinstalled that can help you explore the Graph API. To Access this IDE, Hover on the GraphQL option in the left sidebar and select “GraphiQL IDE”.

![wordpress graphql](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1lvbuuzx7p4eo2eg6ls4.png)

This presents you with an interactive GraphQL IDE, where you can test mutations and queries and see the results in realtime.

![wordpress graphql](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xqhhz6vtxumz12fnmuel.png)

Notice the commented part of the IDE, this is where you write your queries. At the top right you can see the Docs option. This lets you explore the documentation of all the existing Schemas, the arguments they require, types, and return values. The Play icon at the top is what we’d use to run our queries to visualize the result.

![wordpress graphql](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3shtxerjywyob8cx6gw4.png)

---

## Testing Graphql Queries
Let’s write some queries to test our GraphQL endpoint. We’ll fetch all posts, but only their ID and title.

```js
query {
  posts {
    nodes {
        title
        id
      }
  }
}
```
You should see a result like this:

![wordpress graphql query result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lom7kxx9q9zzod0426yz.png)
 
During installation, WordPress automatically creates a dummy post titled “Hello World”. Try creating more posts from your admin dashboard, then come back to the IDE and run the query again.

![wordpress graphql](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gs6mtvj7qq44sm7nsf9j.png)
 
On the sidebar, hover on the “Posts” option and click “Add New”, write some content, and publish.

![create wordpress post](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1pfw2t9zoxomyj7kugyz.png)
 
I have created two more posts and added a category for each of them. Now let’s see the new response from our GraphQL query.

![wordpress graphql result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cbhjcnn4mnt9phyl438o.png)
 
Notice we now have the two new posts that were added. Let’s query the category for each post as well.

![wordpress graphql](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cvbct7zlajjt5etleb0m.png)
 
Here the category for each post is now included in the response. This way we only get the data we need. From the response above, we can see the id of each of these posts, let’s try to query a single post.

```js
query {
 post (id: "cG9zdDo4") {
    title
    date
    featuredImage {
      node {
        sourceUrl
      }
    }
    author {
      node {
        name
        avatar {
          url
        }
      }
    }
    content
    commentCount
    comments {
      nodes {
        author {
          node {
            name
          }
        }
      }
    }
  }
}
```

We should get a response like so:

```js
{
  "data": {
  "post": {
    "title": "Another One!",
    "date": "2021-01-14T00:32:16",
    "featuredImage": {
      "node": {
        "sourceUrl": "[http://localhost:8000/wp-content/uploads/2021/01/ErpnGkxXIAApIWY.jpeg](http://localhost:8000/wp-content/uploads/2021/01/ErpnGkxXIAApIWY.jpeg)"
      }
    },
    "author": {
      "node": {
        "name": "admin",
        "avatar": {
          "url": "http://2.gravatar.com/avatar/2dd6fd016d24468771b83f558e22544c?s=96&d=mm&r=g"
        }
      }
    },
    "content": "\\n<p>Nothing to see here.</p>\\n",
    "commentCount": null,
    "comments": {
      "nodes": []
    }
  }
},
```

![graphql query result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w1152z8oz3wd59flfmuw.png)

---
 
This should give you a basic understanding of how to turn your WordPress website into a GraphQL Server. Next, I’ll show you how to use this data in a Vue.js Application, until then…

Cheers ☕️