Fast Websites with Gridsome And WordPress

Creating fast websites with Vue js, Gridsome and WordPress is easy and you can choose a lot of CMS platforms with open API. This article will show you how to setup Gridsome with WordPress.

Why Vue JS and Gridsome?

You can use an existing WordPress site or other CMS and get the data on build time. Gridsome generates the Vue.js components and the data from your CMS into static files. They are pure HTML, CSS, and javascript files. It loads the static files first then it hydrates the page with new data if necessary. Gridsome splits and Optimizes the code to load scripts per page. One feature I like is image lazy loading and optimation out of the box. Sweet!!!

It uses Apollo GraphQL to query data in which you can query a specific data shape and it will return that shape of data. For instance, with REST API, when you request an API URL, it will return unnecessary data sometimes.

How to get started fast?

You have to install Gridsome CLI to get started. They have a good documentation on the Gridsome site.

yarn global add @gridsome/cli
gridsome create my-gridsome-site
cd my-gridsome-site
yarn develop

First, see how fast it was to set up a template in Gridsome. You have to install the CLI and create a project with the commands above.

Before we set up WordPress, let go over what the process is going to be. Your back-end will be WordPress ( you can choose any CMS platform). You can search on how to install WordPress. You can get a cheap hosting company for the back-end hosting, if you are not doing server-side rendering.

For the front-end which is your generated files build by Gridsome get hosted to a static site hosting company like Netlify. I love their services and is integrated with Github. Awesome!!

Setup WordPress and WP Graphql

Setup the WordPress site or use an existing site in which you want to get the data from. If you have a WordPress website and you want to use the modern framework like Vue JS for its reactivity.

Install WP GraphQL plugin, WP GraphiQL, and WPGraphQL for Advanced Custom Fields.

WP GraphQL gives you a URL to query your data. Gridsome uses Apollo GraphQL for the schema.

You can set up a custom theme to add custom theme functions. Also, you should redirect your back-end URL to the main site.

Setup GraphQL in Gridsome

yarn add gridsome-source-graphql
    {
      use: 'gridsome-source-graphql',
      options: {
        url: 'https://example.com/graphql',
        fieldName: 'wp',
        typeName: 'wpTypes',

        headers: {
          Authorization: `Bearer ${process.env.AUTH_TOKEN}`,
        },
      },
    },

Note: if you get a ServeParseError. Your graphQL url is not getting the data.

You do not need to use the authorization headers for this tutorial. The code above goes in the gridsome.config.js file in plugins array. In this file you can add your SCSS variables and mixins to your Vue components.

You can now run yarn develop in the terminal to build the site and run a server.

http://localhost:8080/ display your site and saved changes to your code.

http://localhost:8080/___explore is your GraphQL query editor.

In the explore page, you can check if it getting the data from WordPress by clicking on the doc tab or schema tab. If you wpTypes you know the plugin is working and we can start querying the database.

Let’s query our data and see what we can get. Go to the GraphQL explore and query the code below to get all your pages.

query {
	pages{
		edges{
      node{
        title
        slug
        content
      }
    }
  }
}

Your data should comeback like the image below:

GraphQL explore page

We can use this query to get all the pages and create routes for them. Below is a way to create pages dynamically.

Go to gridsome.server.js and replace the api.createPages function with the one below.

  api.createPages(async ({ graphql, createPage }) =>{
        // Use the Pages API here: https://gridsome.org/docs/pages-api
        const { data } = await graphql(`
        query {
          pages{
            nodes{
              title
              slug
              id
              pageId
            }
          }
        }
          `)    

        data.pages.nodes.forEach(function(node, index){
          createPage({
            path: `/${node.slug}`,
            component: './src/templates/WP_Page.vue',
            context: {
              id: node.id,
              slug: node.slug,
              title: node.title,
              pageId: node.pageId
            }
          })
        })
  })

This is the WP_Pages.vue component in the templates folder

This will get the pages data. Then loop through and create the pages. Every time you build, you will get the latest data. When you update your back-end, you have to have something to tell Netlify there is an update and please build to display your latest.

<template>
<layout>
    <section class="section">
        <div class="container">
            <h1 v-html="$page.page.title" />
            <div v-if="$page.page.featuredImage" class="featured-image">
                <img src="$page.page.featuredImage.sourceUrl" />
            </div>
            <div v-html="$page.page.content" />
        </div>
    </section>

</layout>
</template>

<page-query>
query Page ($slug: String) {
	page: pageBy(uri: $slug) {
        title
        content
        featuredImage{
            sourceUrl
            altText
        }
	}
}
</page-query>

<script>
    export default {
        metaInfo: {
            title: ''
        }
    }
</script>

<style>

.container {
    max-width: 1200px;
    margin-right: auto;
    margin-left: auto;
}

</style>

We are using the slug to query for the data. The routes should be SEO friendly and human-readable.

To test if everything worked, run the yarn develop command and go to the URL and add a slug name to the address bar. I have a my-account page in WP and to see it works. http://localhost:8080/my-account and your page should so.

my-account page screenshot

You will notice it also brings over the HTML in the content body. If you have an existing WordPress site. You need to add the CSS for content to render properly.

You can access the page query with the $page variable and then follow by the name of the query $page.page.title. You can console.log the $page variable on mounted() and it will print your data.

With this you can create different URL routes. ex. Adding services post type in WordPress and create a route example.com/services/service-url-slug.

Summary

In conclusion, We were able to get a new/existing WordPress site to build a website with Grisdome. You can reach me on my social media channels. What great is you can add animation to the page transitions. Test your new site with GTMetrix or Chrome Audit tools and see how your new site loads.