Wordpress Vue



Over the past several years, I’ve been prying more and more at the limits of the WordPress REST API as they apply to creating ‘headless’ sites and applications. Using the ‘headless’ methodology we can side-step server side rendering (SSR) in favor of JavaScript applications that request data as needed to re-render different views for the site. But it also allows us to decouple the storage of data from the presentation of it, which means that we could have lots of different apps or sites using the same data store in different ways.

WordPress is powerful and Vue is incredibly fun. We offer courses that help you bring them together in exciting ways. We’re industry professionals with over 20 years experience building highly interactive apps and we’re ready to help you get where you want to go. 'vue.wordpress is a Wordpress starter theme built using the WP REST API and Vue.js. It features a Vue-based development workflow with Single File Components and Hot Module Replacement and runs on a single host. Vue.wordpress supports SEO and server rendered content with flexibility in their implementation. PWA for WordPress based on Vue.js. It’s great to see you here 😃 We are commited to delivering high-quality, fuck-up-proof code and which requires both writing unit tests and time to play around the module’s features. Moreover, we not only care about the quality of.

At ALT Lab, we tend to bias towards speed over complexity, but one of the biggest challenges I see Indie Makers face when creating web apps is the need for some kind of persistent data storage that is secure, easy to access, and easy to initiate.

In fact, I believe one of the reasons that the idea of a Spreadsheet as a Database has taken off is BECAUSE these things are difficult to initiate for many people who deal with projects of a smaller scope or with questionable life cycles.

No one wants to npm install Mongoose ORM (Object Relational Mapper) and create a new MongoDB instance for a site, app, or project that may never take off. I think most other Indie Hackers are with me here that the act of making is more important than the technical wizardry we can incant.

In the following blog post, I’ll attempt to describe a pattern of headless web app development using Vue and WordPress that most people who have experience doing basic PHP work in WordPress and front end web development can readily implement.

The Application Use Case

The application we created was meant to help people crowd source Wi-Fi hot spots, so the app has a tight integration with the Google Maps and Google Places APIs to help with the geospatial aspects of this. You can see one of the example screens below:

In terms of the data model, that is also fairly standard with only a few fields.

We store some basic info about the particular place, including the longitude and latitude, and then have the API endpoint calculate a distance from the user based on query string parameters. The resulting object that gets saved looks like this:

There are a lot of interesting aspects to this project, so I’m not going to breakdown all the nuts and bolts of this app and will instead focus on the ‘headless’ aspects of this project. If you’re interested in looking at the source code, you can find it here on GitHub. In the future, I’ll break this out a more specialized starter theme.

Application Architecture

A lot of the examples of Headless WordPress sites out there involve using a separate application stack, like Nuxt or Gatsby for example, to pull from the WordPress API as solely a data store. However, the pattern I’ve chosen to use here allows that same kind of access, but instead of using another stack to pull from WordPress, I developed the guts of a WordPress theme into a flexible SPA (single page application) that reads from and writes to the WordPress API.

Rendering and Routing

To do this, I pared down all of the PHP templates in the theme directory to just the index.php file, so that no matter what route gets hit on the web server, the SPA container gets loaded.

There entire content of the index.php look like this:

This loads a basically blank HTML page with a single div that wraps the SPA.

Later, in the root file of our JavaScript application, we target that div and render all of our Vue components inside of it:

This allows me to do a few different things.

First, using the window.WP_OPTIONS object I can pass data from my WordPress install into the JavaScript application, which allows me to set particular pieces of sensitive data, like the Google API key, in a way that is friendly to WP conventions. I’ll talk about where this comes from in the section about the app’s JavaScript.

Second, since this index file gets rendered every page load, it allows me to use the Vue Router package to define the routes of the application. Since this was a fairly simple application, I only had four total routes with only one of them being dynamic:

It’s worth noting that I only tried this with the router configured to hash mode, which makes URLs that look like this: /#/search

I may play around with HTML5 History Mode, at a later date to see if that would work as well.

Creating APIs

One of the nice things about using the WordPress API is that there is already a commonly used controller pattern for extending the WordPress API with your own routes.

The total API work for this project consisted of one controller file that had three functions that required some actual business logic.

The particular endpoints that I needed to create for this project involve getting a list of items, getting a single item by id, and creating a new item. Hp scanjet 3300c driver xp. Thus, you can see functions in this file tied to those specific routes that execute logic based on the desired outcome.

To activate these routes, all I need to do is require the controller, create a new instance, and initialize it from the theme’s functions.php file:

Doing this makes those routes accessible via the API, but also adds a new namespace to the /wp-json response that documents the routes and their parameters:

To round off the data model for this project, I went ahead and created a custom post type called map-points where we will store this data using certain WP post conventions. This allows us to segregate our data in an understandable way while still allowing people to do some editing of the objects from the WordPress admin area, which is key for less technical users.

Since we’re storing each map-point as a post object, here is a basic mapping of the JSON keys with how they are stored in the database:

Looking at any of the get/create_items function in the API controller should give you an example of how to map your own custom objects onto the WP Post abstraction fairly painlessly.

Front End Code

Since the front end is created using a SPA approach, all of the application UI is authored using Vue single file components, which allow us to create loosely coupled components with scoped styles and functionality. However, to compile all of these Vue templates into JavaScript that we can execute, we need to introduce a build step using Webpack. The JavaScript structure for the project looks like this:

As I develop, Webpack watches for changes in the front end templates and and compiles down to a single JS file in the distdirectory. From there I include the main.jsfile in the WordPress wp_enqueue_scriptshook while also injecting any additional needed data, like site url or a nonce, using the wp_localize_scriptfunction:

Using wp_localize_script we can pass along data that can be helpful to constructing the front end of the application, but we need to create a nonce to authenticate with the REST API for all requests that would require authentication.

If you look at the following example method used when sending a POST request to create a new place in the database, you can see how these global variables get utilized within the Vue component methods:

In the above example, the addNewLocation method invokes the create_item method of MapPointController to add a new map point to the database, mapping the JSON data model we have here to WP post and meta fields. But since we control all of the logic behind each endpoint, we can add in patterns that allow us to do some expressive querying with GET APIs as well.

In the following example, the front end code relies on the Geolocation API in the browser to get the user’s current position, which is then used for a contextual search if available.

When the SearchPage component get mounted, it call the geolocate method, which gets pass a set of success and failure callbacks that both eventually call the getPlaces method with varying parameters. Inside of getPlaces we can see an example of calling the API with an optional set or query parameters. Within the get_items method of the MapPointController those query parameters are examined and influence how the results are returned by ordering the resultant places by distance from the user if provided.

Building a UI with Speed

Wordpress Vue

In addition to the backend parts of this project that helped me get moving quickly, I also employed a few frameworks that helped me speed things along.

The first of which is BootstrapVue, which is really comprehensive collection of Bootstrap 4 components and plugins. Using this, I was able to create what I felt like was a very usable interface for all devices with minimal coding.

I also use the vue2-google-maps package throughout the project to render maps, activate the Google places autocomplete input, and render driving directions. I’ll more than likely write a whole post on this at some point because there are a ton of useful ways to use this particular set of APIs.

Final Thoughts

As yet another iteration of my playing with Vue and the WordPress API, I felt like things have coalesced here in a way that I’m really starting to dig. Part of that for me is identifying clear patterns for wiring the guts of these systems together in a way that provides some meaningful benefit.

Using some fairly simple API controller conventions for WordPress and somewhat breaking the mold for what a theme could be, we arrive at some interesting possibilities for creating powerful things quickly and easily using tools that are widely available.

Webpack Vue.js CLI

Use vue-cli to download vuejs, webpack and template dependencies and create the project in the root of our plugin folder. Navigate to the wp-content/plugins directory.

Update or install globally as needed.

Change to the wordpress plugins directory and use vue-cli to install the webpack-simple template into the new wp-api-vuejs-poc folder. For example,

Here is a tree view of the plugin folders and files at this point. Skip ahead and download or browse the source code if you want.

  • wp-api-vuejs-poc
    • src
      • assets
      • App.vue
      • main.js
    • .bablerc
    • .gitignore
    • class-api-vpoc-page.php
    • index.html
    • package.json
    • README.md
    • webpack.config.js
    • wp-api-vuejs-poc.php

Change back to our new plugin directory, for example wp-api-vuejs-poc.

Install node modules with npm install or npm i.

Development Build

Since the Vuejs app is running in WordPress, we do not need the webpack-dev-server that is included in the vue-cli webpack-simple template.

Uninstall the webpack-dev-server package with npm uninstall using --save-dev option to update the package.json npm manifest.

Update the package.json scripts property so the npm run dev command runs webpack development compilation with watch mode enabled. Watch mode recompiles after every change is saved.

REPLACE

WITH

Vue Resource

We are using vue-resource to make the wp-api requests and handle responses. Install with --save-dev to update the package.json npm manifest.

Page Slug

A front end page template and respective slug is needed to output the app in WordPress on the front end. Last week, I wrote a quick post with details on how to do this. The slug value, api-test is set in the class-api-vpoc-page.php file.

This proof-of-concept was tested with WordPress permalink settings set to Post name.

Let’s do a build to make sure everything is hooked up properly at this point.

After the build, you should now have a dist folder in the plugin root containing the javascript and any other static assets.

Login to WordPress and Activate the plugin. Then navigate to the front end page, for example, http://wordpress.dev:8080/api-test/. You should see the default vue-cli template content.


Default App build

Vue App Component

Open up the src/App.vue file and replace the contents with the following containing our post form, vue model and submit handler.

App.vue

Open up the src/main.js file and replace the contents with the following javascript. Included is the Vue resource settings for the X-WP-Nonce WordPress security token in the request header.

main.js

Build the App

Manually refresh the api-test page to verify the build. You should now have a working front end form to Submit a Post.


Submit Post Form

Versions that were used in this tutorial.

  • WordPress 4.7
  • Vue v2.1.0
  • Vue-cli v2.6.0
  • Vue-resource v1.0.3
  • Webpack v2.1.0-beta.25

Wordpress View Html

Vuetify
Source Code

The next page covers using axios, jQuery and other methods for making web requests instead of vue-resource.

Axios

Axios is a popular HTTP client library that covers almost everything vue-resource provides with a similar API.

Install Axios

To simplify using Axios in our Vue app, install the vue-axios wrapper for Vue integration.

Code Updates

Update src/main.js as follows.

main.js

Update src/App.vue as follows.

REPLACE

WITH

Rebuild the App

Free Dark Wordpress Themes

Uninstall vue-resource

Refresh the api-test page and Submit a post to confirm the build and app are working as expected.

The axios-p01 tag in the wp-api-vuejs-poc source code repository on GitHub has been updated to use axios instead of vue-resource for ajax requests:

Source Code

jQuery

Since jQuery is loaded by default in WordPress, we can use its ajax asynchronous HTTP method for the API request.

Code Updates

Remove all of the vue-resource code in src/main.js. Billiards near me.

Headless Wordpress Vue

main.js

Replace the script block code in src/App.vue as follows.

Wordpress vue plugin

Wordpress Vue

The global jQuery object needs to be available to the app to use its ajax method. Add the externals option to the webpack.config.js and specify jquery so it can be declared as a dependency.

The jquery-p01 tag in the wp-api-vuejs-poc source code repository on GitHub has been updated with these changes. The vue-resource plugin is removed and replaced with the ajax method available in the external jQuery library loaded by default in WordPress:

Source Code

Part II

Part 2 of this series covers adding the following to the Vue.js front end WordPress application.

Wordpress Views And Visitors

  • List posts submitted by the current user
  • Select from the list to edit a post
  • Delete a post from the list

Resources

Please enable JavaScript to view the comments powered by Disqus.comments powered by Disqus