DEV Community

Cover image for Building a Headless WordPress Site With Vue.js
Pieces 🌟
Pieces 🌟

Posted on • Edited on • Originally published at code.pieces.app

Building a Headless WordPress Site With Vue.js

Cover image of a window that has WordPress opened up with plugins available screen.

For both developers and non-developers who want to build and produce beautiful websites rapidly, WordPress has become the go-to content management system. Businesses have more precise control over the content management backend when using a Headless WordPress. Additionally, they are allowed to use any frontend of their choosing, such as Angular, React, or Vue.

This guide will go into great detail regarding headless WordPress, including what it is, when to use it, the benefits of headless WordPress, and why you should consider using a headless CMS. In the final section, we'll look at setting up a headless WordPress environment and developing the front end with Vue.js.

What is Headless WordPress?

If you've been in the CMS industry for a while, you probably already know that WordPress is regarded as what they call a "monolithic" CMS. You have a strong backend where you can create and manage content, and it’s still made with the front-end experience in mind. With the aid of WordPress, it’s also possible to incorporate display functionality utilizing themes and plugins that fuse the front and back ends together.

WordPress can be used as a wonderful content management system. You can expand your content control beyond your theme by using the REST API that WordPress offers.

Headless WordPress differs from the current WordPress, which is more proactive and pushes or delivers content to mostly browser-based sites. When using a Headless CMS WordPress, you can still use the back-end functionality of the WordPress platform, but it will change into a reactive system, meaning the content will automatically differ based on the characteristics of the front-end website where the content is viewed.

What is Vue.js?

A framework for creating progressive user interfaces is called Vue. Vue, in contrast to other unitary frameworks, is designed to be adopted gradually. Since the core library is solely focused on the display layer, integrating it with other libraries or pre-existing projects is straightforward. On the other hand, Vue is perfectly capable of powering complex Single-Page Applications when used in conjunction with modern technologies and supporting libraries such as WordPress. Need more information? Check out getting started with Vue.js for a more in-depth introduction.

How to Integrate Vue.js with WordPress

The first thing we need to do is set up a WordPress site because it will serve as the major source of data for all of the front-end technologies we utilize.

The use of a Rest API enables programmers to communicate with cross-technology interfaces, provided that both parties can speak JSON. The JSON format is used for the data that is produced by the Rest API. The Rest API is enabled by default; but, you can restrict Rest API access if you so choose. For this project, we won't be modifying that.

Prerequisites

  • An active WordPress installed/running
  • knowledge of Vue basics

On your WordPress blog Dashboard, go to Settings, select Permalinks, and tick either Post name or Custom Structure. I’ll be going with Post name.

WordPress blog Dashboard Post name - Example Image.

Download the Postman Chrome extension now that we are using API calls. Open the Postman extension and enter the URL using the guidelines below.

https://example.com/wp-json/wp/v2/posts
Enter fullscreen mode Exit fullscreen mode

But, if you are running on localhost for development purposes, input the URL below on your Postman Desktop Agent (not the Chrome extension this time).

http://localhost/wordpress/wp-json/wp/v2/posts
Enter fullscreen mode Exit fullscreen mode

The post data on your WordPress site will be fetched using the aforementioned URL.

Wordpress fetched using the aforementioned URL - Example image.

Above, we have our data from our REST API in JSON format. Here's the structure you should see after a GET request:

{
        "id": 5,
        "date": "2022-10-01T12:57:47",
        "date_gmt": "2022-10-01T12:57:47",
        "guid": {
            "rendered": "http://localhost/wordpress/?p=5"
        },
        "modified": "2022-10-01T15:19:58",
        "modified_gmt": "2022-10-01T15:19:58",
        "slug": "ejiro-thankgod",
        "status": "publish",
        "type": "post",
        "link": "http://localhost/wordpress/ejiro-thankgod/",
        "title": {
            "rendered": "Ejiro ThankGod"
        },
        "content": {
            "rendered": "\nHello! just trying things out alright\n",
            "protected": false
        },
        "excerpt": {
            "rendered": "<p>Hello! just trying things out alright</p>\n",
            "protected": false
        },
        "author": 1,
        "featured_media": 0,
        "comment_status": "open",
        "ping_status": "open",
        "sticky": false,
        "template": "",
        "format": "standard",
        "meta": [],
        "categories": [
 1
        ],
  }
Enter fullscreen mode Exit fullscreen mode

Notice we have the id, slug, date, title, and, of course, the content which we’ll set up on our Vue.js website.

Setting Up the Vue Front-end

The Wordpress Headless CMS will be used for the project's whole backend content management, while Vue.js will handle the project’s frontend display of our content. Get ready to start your journey as a Vue.js front-end developer.

Prerequisites

  • NodeJS & NPM
  • Vue CLI
  • Text Editor, such as Sublime or VS Code

After setting up the environment with the Vue command line, run the following command on the terminal and follow the prompts to create a Vue app.

vue create <app name>
Enter fullscreen mode Exit fullscreen mode

Run the following command after the project has been created to view the Vue app project output at http://localhost:8080.

npm run serve
Enter fullscreen mode Exit fullscreen mode

The project source code should then be opened in the code editor of your choice; this is where we'll actually start writing code.

Add the following code to your App.vue file:

<template>
  <div>
    <ul v-for="post in posts" v-bind:key="post.id">
      <li>
        <h2>{{ post.title.rendered }}</h2>
      </li>
      <p>{{ post.content.rendered }}</p>
    </ul>
  </div>
</template>
<script>
export default {
  data() {
 return {
      posts: [],
    };
  },
  methods: {
 async getData() {
 try {
 let response = await fetch(
 "http://localhost/wordpress/wp-json/wp/v2/posts"
        );
 this.posts = await response.json();
      } catch (error) {
        console.log(error);
      }
    },
  },
  created() {
 this.getData();
  },
};
</script>
Enter fullscreen mode Exit fullscreen mode

Line-by-line explanations of the aforementioned block of code in the methods property will follow.

async getData() {
 try {
        let response = await fetch(
 "http://localhost/wordpress/wp-json/wp/v2/posts"
        );
 this.posts = await response.json();
      } catch (error) {
        console.log(error);
      }
Enter fullscreen mode Exit fullscreen mode

The getData method has the async keyword appended to it to indicate that it will employ promises. We'll use this keyword along with await to halt the function's execution until the promise is fulfilled.

A block of code that will be tested for errors while it is performed is defined by the try attribute. The fetch method is used to retrieve data from the URL in the block of code let response = await fetch('http://localhost/wordpress/wp-json/wp/v2/posts');.

Considering that the fetch function will return a promise, await is prefixed to the request. The information returned by the API following the fulfillment of the promise will be kept in the variable response.

Using the v-for directive to loop through the posts, we can now display the data in the template.

<ul v-for="post in posts" v-bind:key="post.id">
      <li>
       <h2>{{ post.title.rendered }}</h2>
      </li>
      <p>{{ post.content.rendered }}</p>
    </ul>
Enter fullscreen mode Exit fullscreen mode

Now if we check our Vue front-end, we can see the post we made from the WordPress site. Basically, all we have to do is beautify our front-end website and add more API calls.

The post we wrote as it appears on the site.

What are the benefits of Headless CMS

  • A single headless CMS instance can handle an unlimited number of digital channels rather than having to create several, parallel content management system instances, for example, to support web and mobile channels.
  • In a headless CMS, code and content are separated, making it simpler for content writers to ignore the code and concentrate solely on the material that is their responsibility.
  • Developers, meanwhile, are not restricted to a proprietary language or other features of a certain content management system but can utilize all the most recent tools and frameworks to create content experiences on any modern platform.
  • Without being constrained by a proprietary language or other restrictions of a certain content management system, developers can use all the most recent tools and frameworks to bring content experiences to life on any modern platform.

Conclusion

With a Headless WordPress CMS, you will get all the benefits of a headless CMS system for editing rich content like WordPress, plus the performance and security benefits of Vue.js. Now that you have set up Headless Wordpress and your content production is separated from your development stack, you are able to build your own app with the help of an up-to-date JavaScript framework and a thriving ecosystem. You will have access to all the features you need for your website to expand thanks to the frontend functionality in Vue and the backend functionality in WordPress.

If you found this article to be helpful be sure to check out how to sanity.io as a headless CMS in Next.js. Learn how you can create text, images, and other media types with Sanity.io and display that content in your Next.js application.

Resources

Top comments (0)