Learn How to Create a Headless WordPress Site With Vue.js

Creating a headless WordPress site with Vue.js is a great way to create a modern, dynamic website. Headless WordPress sites are becoming increasingly popular as they allow developers to create a website that is both fast and secure.

1. Install WordPress

The first step in creating a headless WordPress site with Vue.js is to install WordPress. You can do this by downloading the WordPress software from the official website and following the instructions to install it on your server.

2. Install Vue.js

Once WordPress is installed, you will need to install Vue.js. You can do this by downloading the Vue.js library from the official website and following the instructions to install it on your server.

3. Create a Theme

Once Vue.js is installed, you will need to create a theme for your headless WordPress site. You can do this by creating a new folder in the WordPress themes directory and adding the necessary files.

4. Create a Plugin

Once your theme is created, you will need to create a plugin to enable the headless WordPress site. You can do this by creating a new folder in the WordPress plugins directory and adding the necessary files.

5. Configure the Plugin

Once your plugin is created, you will need to configure it to enable the headless WordPress site. You can do this by adding the necessary code to the plugin file and configuring the settings.

6. Create the Frontend

Once your plugin is configured, you will need to create the frontend of your headless WordPress site. You can do this by creating a new folder in the WordPress themes directory and adding the necessary files.

7. Connect the Frontend and Backend

Once the frontend is created, you will need to connect it to the backend of your headless WordPress site. You can do this by using the WordPress REST API to make requests to the WordPress database.

8. Test and Deploy

Once everything is connected, you will need to test and deploy your headless WordPress site. You can do this by running the necessary tests and deploying the site to a live server.

Creating a headless WordPress site with Vue.js is a great way to create a modern, dynamic website. By following the steps outlined above, you can create a headless WordPress site that is both fast and secure.
[ad_1]

WordPress has been the go-to content management system for developers and non-developers to quickly build and create stunning websites.

Using a microservice architecture, where the content management backend is separate from the frontend, allows maximum control of both the “ends.”  This separation problem is what headless content management systems, including headless WordPress solutions, try to solve.

With a headless approach, businesses have more granular control over the content management backend. They’re also free to use any frontend of their choice, including React, Vue, Angular, etc.

This guide will explore in detail headless WordPress, and what it is all about, when and why you should consider using it. Lastly, we will explore creating a headless WordPress environment, building out the frontend with Vue.js, and deploying the headless WordPress using Kinsta.

What Is Headless WordPress?

WordPress is a monolith application where the backend and the frontend parts are tightly wound together. The backend is where the management comes in, where you can create, edit, add, and delete content, including changing appearance configurations. In contrast, the frontend is responsible for displaying the content to the user.

Headless WordPress is the term used to describe decoupled WordPress. The backend (management) part is separate from the frontend part of the WordPress CMS. You can develop and manage the frontend as a standalone application with any frontend framework of your choice.

Pros and Cons of Headless WordPress

Next, we will explore the pros and cons of headless WordPress to give you a better understanding of the concept.

The Pros

First, we’ll start by exploring the pros.

Super-Fast Performance

In this era of super-fast performing applications, your website should not take more than a few seconds to load and avoid losing visitors. Since the frontend is separated from WordPress and can be developed with high-performance and scalability in mind using modern frontend tools, employing a headless WordPress approach is of great benefit to the overall user experience of your website.

Granular Control

Opting for headless architecture gives you more control over your design layout, content presentation, and how users interact with the frontend of your application. It also allows your backend content to be secured and accessed from a central location.

Increased Scalability

Scaling WordPress can be complicated sometimes because you don’t have complete control of all the components and codes that powers WordPress, mainly if you aren’t a developer. But with the decoupling of WordPress, it is effortless to scale each part in isolation, and you can easily detect which part needs scaling.

Tighter Security

We can not stress the security benefits of headless WordPress enough since decoupled WordPress has high-security benefits against hackers and DDoS attacks. The headless WordPress approach makes it difficult for hackers to access your sensitive backend data since it is separate from your frontend, the user-facing website.

Lightweight Design

You will have more control over the structure and layout of your frontend design. In addition, you can work on the frontend with more freedom and customized design; thanks to the REST API calls, you’ll be able to take advantage of modern web tools and deploy them on the frontend.

Multi-Channel Content Publishing

Since headless WordPress uses an API-based system to communicate your content to the frontend, you can display your content anywhere and on any platform, including desktop, website, mobile apps, and touch screen kiosk. It is also possible to make full use of Augmented Reality, Virtual Reality, and Internet of Things devices to display and present your content coming from the API-based system.

The Cons

We’ll explore the cons of headless in more depth as we go, but its main drawbacks are:

  1. Separating the backend and the frontend gives you an extra load when managing different website instances.
  2. It can be costly to implement since it needs additional members on your team and extra capital for running different instances.
  3. Making your content available on different platforms can cause an inconsistent experience for your users if the content is not presented consistently across all platforms.

When Headless WordPress Might Not Be the Best Option

Since headless WordPress is an incredible innovation with great benefits, there are some things you use to keep in mind when deciding whether or not you should go with it.

  1. Headless WordPress is very expensive to maintain. You will maintain two different instances of one website from infrastructure to multiple developers.
  2. Headless WordPress does not support all features of WordPress. For instance, great WordPress features like the WYSIWYG editor and live preview won’t work when using a separated frontend.
  3. It is more expensive to set up a headless WordPress. Hence, always keep its increased cost in mind.

Who Should Use Headless WordPress?

Below are the best suitable cases that you may require headless WordPress:

  1. You should be using headless WordPress if the security of your website is your top concern and paramount to your company.
  2. Next, if your website does not need regular upgrading and updating, it will be a great sign that you need to use a headless setup.
  3. Next, if you want to have a customized design that a WordPress theme won’t easily do, you want to spice the frontend of your website up with a unique design. Then, headless WordPress is your next option.
  4. Lastly, if you’re building a short lifespan website or a demo site for presentations and tutorials, then you can try out the headless approach.

Who Should Avoid Using Headless WordPress

Here are several cases in which using headless WordPress is not a good option:

  1. When your website relies solely on specific plugins and functionalities that control and work best with the frontend of your application, you should stick with WordPress unless the plugins offer API-based options to consume the data.
  2. Suppose you’re not interested in coding your website, or your website requires daily maintenance, and you’re not hiring a professional for routine maintenance due to your low budget. In that case, WordPress is a suitable option for you.
  3. If you’re not a seasoned developer and want to create and manage your website alone, you should be using WordPress.

How To Make WordPress Headless (Build an App)

This section will explore building and developing a news blog with headless WordPress for the backend and Vue 3 as the user-facing frontend.

Setting Up Headless WordPress With Devkinsta

We will develop the headless WordPress with DevKinsta, a popular WordPress local development environment to design, develop, and deploy WordPress sites from the comfort of your local machine.

DevKinsta is free forever and offers you great benefits and comfort in developing and building WordPress with it.

You can download and install DevKinsta from the official website and follow the instructions in the documentation to get started.

Since we have DevKinsta installed already, we will open it and follow the step below to set up our first headless WordPress.

On the DevKinsta dashboard, create a new WordPress site using Nginx, MySQL, and any WordPress version available. Also, you can import an existing WordPress instance or create a custom WordPress instance from the dashboard.

Next, give your newly created WordPress instance a name, admin username, and password, then click on Create and copy out the details while DevKinsta creates a new WordPress instance in your local machine.

Next, click on Open Site to open your newly created WordPress instance on your default browser.

Lastly, you can log in to the admin dashboard by accessing the http://headless-wordpress-news-blog.local/wp-admin link and typing in the admin login credentials you entered when creating the new instance.

Note that we have set up our headless WordPress locally with the URL http://headless-wordpress-news-blog.local with the frontend is hosted locally at http://news-blog.local, and we will be using it throughout the tutorial.

Configuring Our Headless WordPress

Next, after successfully logging into your WordPress dashboard, you can go ahead to install any plugins and configuration of your choice.

We will disable the theme entirely for this tutorial and only access the content via WordPress REST API-based endpoint by installing the Simple Website Redirect plugin and setting it up.

Go to Plugins > Add new and search for the Simple Website Redirect, install and activate it:

The WordPress plugin installation screen.
WordPress plugin installation.

Next, click on the plugin Settings and input your frontend-based URL (e.g. http://news-blog.local), click on the Advanced setting options and add the following paths — /wp-admin, /wp-login.php, and /wp-json — to the Exclude Paths section.

Lastly, enable the Plugin by selecting Enabled in the Redirect Status dropdown:

Simple Website Redirect plugin settings page.
Simple Website Redirect plugin settings.

…and that’s it!

In addition, if your JSON API is not enabled when you visit http://headless-wordpress-news-blog.local/wp-json by default, you can enable it by opening your Permalinks under WordPress Settings and selecting Post Name or any other one of your choice except Plain:

The WordPress Permalink settings page.
WordPress Permalink settings.

Now when you visit your http://headless-wordpress-news-blog.local/wp-json, it should present you with JSON data like below:

{
  "name": "Headless WordPress News Blog",
  "description": "Just another WordPress site",
  "url": "http://headless-wordpress-news-blog.local",
  "home": "http://headless-wordpress-news-blog.local",
  "gmt_offset": "0",
  "timezone_string": "",
  "namespaces": [
    "oembed/1.0",
    "wp/v2",
    "wp-site-health/v1"
  ],
  "authentication": [
    
  ],
  "routes": {
    "/": {
      "namespace": "",
      "methods": [
        "GET"
      ],
      "endpoints": [
        {
          "methods": [
            "GET"
          ],
          "args": {
            "context": {
              "default": "view",
              "required": false
            }
          }
        }
      ],
...

Setting Up Vue.js (Frontend)

We will be using the Vite web development tool to create our Vue 3 application to connect with headless WordPress. You can read more about Vue 3 and Vite development tools.

In this article, we will be building a news blog. All the backend content management of the project will be developed and hosted with our headless WordPress using Devkinsta.

Type along with these simple commands:

npm init @vitejs/app news-blog
cd news-blog
npm install
npm run dev

If you’re having issues with spaces in your username, try using:

npx create-vite-app news-blog

Note that we have configured our Vue 3 application to listen to http://news-blog.local, but you can stick with the default http://localhost:3000.

Lastly, open your Vue 3 codebase with any code editor of your choice. We will go with VSCode, and let’s get our hands dirty with codes.

Consuming WordPress API

We have gone ahead to develop the remaining part of the Vue application to save you reading time, but you can go ahead to clone the repository from my GitHub.

Display App Post Component

The code snippet below shows how we implement the WordPress REST API with our Vue instance to display all the posts from the headless WordPress:

<template>
  <section>
    <div class="padding-top">
      <div class="container inner-padding-top">
        <div class="row">
          <div class="col-md-12 col-sm-12-col-xs-12 text-center">
            <h2 class="lead-title text-uppercase">
              Latest Backend Dev. Articles
            </h2>
            <h3 class="article-subtitle">
              Latest Backend Dev. Articles curated daily by the community.
            </h3>
          </div>
        </div>
        <div class="row mb-1 mt-5">
          <post v-for="(post, i) in posts" :key="i" :post="post" />
        </div>
      </div>
    </div>
    <div class="col-md-12 col-sm-12-col-xs-12 text-center mb-5">
      <Button link="/posts" class="col p-3">More Articles</Button>
    </div>
  </section>
</template>

<script>
import { mapState } from 'vuex'
export default {
  computed: {
    ...mapState({
      posts: (state) => {
        return [...state.post.posts].slice(0, 22)
      },
    }),
  },
}
</script>

Display Single Post Component

The code snippet shows how we retrieve a single post with WordPress REST API with the headless WordPress and display it in our Vue instance:

<template>
  <div class="card single">
    <div class="card-head pl-3 pr-3 pt-3">
      <h1 class="title">{{ post.title || '' }}</h1>
      <div class="d-flex">
        <div class="author d-flex pr-3 pb-4">
          <div class="profile mr-2"></div>
          <a :href="'/authors/' + post.author.slug" class="subtitle is-6">
            {{ post.author.name }}
          </a>
        </div>

        <div class="date_created">
          <small class="text-muted">
            <li class="fa fa-calendar"></li>
            <time
              :datetime="$moment(post.date).format('MMMM Do YYYY, h:mm:ss a')"
              >{{ $moment(post.date).format('MMMM Do YYYY') }}</time
            >
          </small>
        </div>
      </div>
    </div>
    <div class="block-image pl-3 pr-3 pt-2 mb-3">
      <img
        v-lazy-load
        :data-src="image"
        class="card-img-top img-fluid"
        :alt="post.title"
      />
    </div>

    <div class="tags absolute">
      <a
        v-for="category in post.categories"
        :key="category.id"
        :href="'/categories/' + category.slug"
        class="btn-tag"
      >
        {{ category.title }}
      </a>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'

export default {
  name: 'SinglePost',
  props: {
    post: {
      type: [Object, Array],
      default: () => {},
    },
  },
}
</script>

Below is the store that makes the API calls to the headless WordPress API for the backend contents:

export const actions = {
  async getPosts({ commit }, { page, count = 22 }) {
    try {
      const response = await fetch(
        `http://headless-wordpress-news-blog.local/wp-json/wp/v2/posts`
      )
      const data = await response.json()
      if (data) {
        commit('setPosts', data)
      }
      return data
    }
  },
  
 async getPost({ commit }, id) {
    try {
      const response = await fetch(
        `http://headless-wordpress-news-blog.local/wp-json/wp/v2/posts/${id}`
      )
      const data = await response.json()
      if (data) {
        commit('setPost', data)
      }
      return data
    }
  },
 }

Deploying Headless WordPress With Kinsta

Lastly, deploying your headless WordPress is made very easy with DevKinsta using the Kinsta hosting service.

To deploy your headless WordPress to Kinsta, click on the Push to Staging button on your DevKinsta dashboard and sign in to Kinsta with your login credentials.

You can learn how to push changes to the staging environment to deploy your headless WordPress to Kinsta hosting services in a single click.

Lastly, you can deploy your Vue.js instance to any cloud hosting provider of your choice. Make sure to update your headless WordPress endpoint accordingly to test your application in a live production environment.

Summary

Headless WordPress and the benefits it comes with are here to stay for a while. Its popularity will only continue to grow as more developers and site owners come to understand the upsides of a headless option.

In this guide, we’ve introduced you to headless WordPress’ benefits, pros, and cons, and we’ve shown you how to build and deploy your first headless WordPress with DevKinsta. You’re now well on your way to having your headless WordPress implementation.

What are your tips for deploying a headless WordPress site? Please share them in the comments section!



[ad_2]

Source link

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

GSTIN is 03EGRPS4248R1ZD.

Contact
Jassweb, Rai Chak, Punjab, India. 143518
Item added to cart.
0 items - 0.00