8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 | # Vue.wordpress
3 |
4 | > A Wordpress starter theme built using the WP REST API and Vue.js. Optimized for SEO, performance, and ease of development.
5 |
6 | *This theme is intended to be used as a foundation for creating sites that function as a single-page application (SPA) on the front-end, while using Wordpress and the WP REST API to manage content and fetch data.*
7 |
8 | **Check out [a demo of the theme](http://vue-wordpress-demo.bshiluk.com)**
9 |
10 | # Table of Contents
11 |
12 | - [Features](#features)
13 | - [Libraries](#libraries)
14 | - [Usage](#usage)
15 | - [Development](#development)
16 | - [Deployment](#deployment)
17 | - [General Overview](#general-overview)
18 | - [Routing](#routing)
19 | - [Permalinks to Routes](#permalinks-to-routes)
20 | - [Exceptions](#exceptions)
21 | - [Notes on Permalink Structure](#notes-on-permalink-structure)
22 | - [Category and Tag Base](#category-and-tag-base)
23 | - [Homepage and Posts Per Page](#homepage-and-posts-per-page)
24 | - [Internal Link Delegation](#internal-link-delegation)
25 | - [State Management and API Requests](#state-management-and-api-requests)
26 | - [Vuex Initialization and Schema](#vuex-initialization-and-schema)
27 | - [Schema](#schema)
28 | - [Initialization](#initialization)
29 | - [Requesting Data](#requesting-data)
30 | - [Making WP REST API Requests](#making-wp-rest-api-requests)
31 | - [Request Caching](#request-caching)
32 | - [Actions Api Reference](#actions-api-reference)
33 | - [Request an item of type by its slug](#request-an-item-of-type-by-its-slug)
34 | - [Request an item of type by its id](#request-an-item-of-type-by-its-id)
35 | - [Request a list of items](#request-a-list-of-items)
36 | - [Getters Api Reference](#getters-api-reference)
37 | - [Get an item of type by slug](#get-an-item-of-type-by-slug)
38 | - [Get an item of type by id](#get-an-item-of-type-by-id)
39 | - [Get a list of items](#get-a-list-of-items)
40 | - [SEO](#seo-and-server-rendered-content)
41 | - [How It Works](#how-it-works)
42 | - [The Three Basic Approaches](#the-three-basic-approaches)
43 | - [Pseudo Headless](#pseudo-headless)
44 | - [Example index.php](#example-indexphp)
45 | - [Pseudo Headless SEO](#pseudo-headless-seo)
46 | - [Preload Data](#preload-data)
47 | - [Example single.php](#example-singlephp)
48 | - [Example category.php](#example-categoryphp)
49 | - [Preload Data SEO](#preload-data-seo)
50 | - [Progressive Enhancement](#progressive-enhancement)
51 | - [Example home.php](#example-homephp)
52 | - [Progressive Enhancement SEO](#progressive-enhancement-seo)
53 | - [Upcoming Features](#upcoming-features)
54 | - [Final Thoughts](#final-thoughts)
55 |
56 | ## Features
57 | * Front and Back-End run on same host
58 | * Supports various client/server code partitioning strategies for optional SEO optimization
59 | * Hot Module Replacement ( HMR ) for development
60 | * Vue.js Single File Components
61 | * Production / Development Webpack configurations
62 | * Dynamic routing as set up in WP Dashboard ( Settings > Permalinks )
63 | * Vue Router internal link delegation ( no need to use `` in components )
64 | * Document title tag update on route change
65 | * Consistent in-component REST API data fetching
66 | * Integrated REST API request caching and batching
67 | * [REST API Data Localizer](https://github.com/bucky355/rest-api-data-localizer) for state initialization and making back-end REST API requests
68 | * Normalized data structure
69 | * Pagination enabled
70 | * Utility components, including ResponsiveImage, SiteLoading, ArchiveLink, e.t.c.
71 |
72 | ## Libraries
73 | To promote flexibility in implementation, styling and dependencies are limited. That said, the theme requires the following libraries:
74 | * [Axios](https://github.com/axios/axios)
75 | * [Vue.js](https://vuejs.org/v2/guide/)
76 | * [Vue Router](https://router.vuejs.org/)
77 | * [Vuex](https://vuex.vuejs.org/)
78 |
79 | ## Usage
80 |
81 | 1. Clone or download this repo in your `/wp-content/themes` directory and activate
82 | 2. Clone or download the [REST API Data Localizer](https://github.com/bucky355/rest-api-data-localizer) companion plugin in your `/wp-content/plugins` directory and activate.
83 | 3. Ensure settings in Settings > Permalinks do not violate rules as described in [Routing](#routing).
84 | 4. Install dependencies `npm install`.
85 | 5. Build the theme `npm run build`
86 |
87 | ### Development
88 |
89 | 1. Start development with HMR `npm run dev`
90 | 2. Edit `functions.php` so Wordpress enqueues the bundle served from webpack dev server
91 | ````php
92 | // Enable For Production - Disable for Development
93 | // wp_enqueue_script('vue_wordpress.js', get_template_directory_uri() . '/dist/vue-wordpress.js', array(), null, true);
94 |
95 | // Enable For Development - Remove for Production
96 | wp_enqueue_script( 'vue_wordpress.js', 'http://localhost:8080/vue-wordpress.js', array(), false, true );
97 | ````
98 | ### Deployment
99 |
100 | 1. Build the theme `npm run build`
101 | 2. Only include Wordpress theme files ( i.e. `style.css`, `functions.php`, `index.php`, `screenshot.png` e.t.c.) and the `/dist/` directory
102 | 3. Edit `functions.php` so Wordpress enqueues the bundle served from your `/dist/` directory
103 | ````php
104 | // Enable For Production - Disable for Development
105 | wp_enqueue_script('vue_wordpress.js', get_template_directory_uri() . '/dist/vue-wordpress.js', array(), null, true);
106 | ````
107 |
108 | ## General Overview
109 |
110 | 1. Wordpress creates initial content and localizes a `__VUE_WORDPRESS__` variable with initial state, routing info, and any client side data not accessible through the WP REST API.
111 | 2. Client renders initial content, and once js is parsed, `__VUE_WORDPRESS__` is used to create the Vuex store, Vue Router routes, and the app is mounted.
112 | 3. Vue takes over all future in-site navigation, using the WP_REST_API to request data, essentially transforming the site into a SPA.
113 |
114 | ## Routing
115 |
116 | ### Permalinks to Routes
117 |
118 | By default, routing works as defined in Settings > Permalinks. You can even define a custom structure.
119 |
120 | 
121 |
122 | ✔️ 'Day and Name' `/%monthnum%/%day%/%postname%/`
123 |
124 | ✔️ 'Month and Name' `/%year%/%monthnum%/%day%/%postname%/`
125 |
126 | ✔️ `/my-blog/%category%/%postname%/`
127 |
128 | ✔️ `/%postname%/%author%/%category%/%year%/%monthnum%/`
129 |
130 | ### Exceptions
131 |
132 | Using 'Plain', 'Numeric', or any custom structure that uses `%post_id%` as the sole identifier.
133 |
134 | ❌ `/%year%/%monthnum%/%post_id%/`
135 |
136 | ❌ `/archives/%post_id%/`
137 |
138 | *However, if you combine the `%post_id%` tag with the `%postname%` tag it will work.*
139 |
140 | ✔️ `/%author%/%post_id%/%category%/%postname%/`
141 |
142 | *If for some reason you're set on using the post id in your permalink structure, editing the `Single.vue` component to use id as a prop and fetching the post by id instead of slug should make it work.*
143 |
144 | Using 'Post name'
145 |
146 | ❌ `/%postname%/`
147 |
148 | *However, you can add a base to make it work*
149 |
150 | ✔️ `/some-base/%postname%/`
151 |
152 | ### Notes on Permalink Structure
153 |
154 | - Using `/%category%/%postname%/` or `/%tag%/%postname%/` will cause problems with nested pages
155 | - Problems with the permalink structure are generally because the router can't differentiate between a post and a page. While this may be solved with Navigation Guards and in component logic to check data and redirect when necessary, the introduced complexity is out of scope for this starter theme.
156 | - Routes for custom post types will be needed to be added as needed.
157 | - Routing is by default dynamic, however when a structure is defined it could be in the best interest of the developer to refactor out some of the dynamic qualities.
158 |
159 | ### Category and Tag Base
160 |
161 | If you want to edit the category and tag permalink bases within the same Settings > Permalinks screen, that is supported as well.
162 |
163 | ### Homepage and Posts Per Page
164 |
165 | Additionally, in Settings > Reading you can adjust what your home page displays and posts shown per page ( labeled 'Blog pages to show at most' ).
166 |
167 | ### Internal Link Delegation
168 |
169 | Within a Vue application, all links not implemented with `` trigger a full page reload. Since content is dynamic and managed using Wordpress, links within content are unavoidable and it would be impractical to try and convert all of them to ``. To handle this, an event listener is bound to the root app component, so that all links referencing internal resources are delegated to Vue Router.
170 |
171 | *Adapted from Dennis Reimann's [Delegating HTML links to vue-router](https://dennisreimann.de/articles/delegating-html-links-to-vue-router.html)*
172 |
173 | This has the added benefit of being able to compose components using the 'link' property returned from WP REST API resources without having to convert to a relative format corresponding to the router base for ``.
174 |
175 | Instead of:
176 | ````html
177 | {{ tag.name }}
178 | ````
179 | You can do:
180 | ````html
181 | {{ tag.name }}
182 | ````
183 |
184 | ## State Management and API Requests
185 |
186 | A Vuex store is used to manage the state for this theme, so it is recommended at the very least to know [what it is](https://vuex.vuejs.org/) and become familiar with some of the [core concepts](https://vuex.vuejs.org/guide/state.html). That said, you'd be surprised at the performant and user-friendly themes you can build without even modifying the Vuex files in `/src/store/`.
187 |
188 | ### Vuex Initialization and Schema
189 |
190 | Normally, you would find the schema ( structure ) of a Vuex store in the file that initializes it (or an imported state.js file ). Even though it is initialized in `/src/store/index.js`, the schema is defined in `functions.php`. This allows you to use the use the [REST API Data Localizer](https://github.com/bucky355/rest-api-data-localizer) to prepopulate the store with both WP REST API data in addition to any other data you may need for your state not available through the WP REST API.
191 |
192 | #### Schema
193 | ````php
194 | // functions.php
195 |
196 | new RADL( '__VUE_WORDPRESS__', 'vue_wordpress.js', array(
197 | 'routing' => RADL::callback( 'vue_wordpress_routing' ),
198 | 'state' => array(
199 | 'categories' => RADL::endpoint( 'categories'),
200 | 'media' => RADL::endpoint( 'media' ),
201 | 'menus' => RADL::callback( 'vue_wordpress_menus' ),
202 | 'pages' => RADL::endpoint( 'pages' ),
203 | 'posts' => RADL::endpoint( 'posts' ),
204 | 'tags' => RADL::endpoint( 'tags' ),
205 | 'users' => RADL::endpoint( 'users' ),
206 | 'site' => RADL::callback( 'vue_wordpress_site' ),
207 | ),
208 | ) );
209 | ````
210 |
211 | #### Initialization
212 | As you can see below, the `__VUE_WORDPRESS__.state` key is used to initialize the Vuex store.
213 |
214 | ````js
215 | // src/store/index.js
216 |
217 | const { state } = __VUE_WORDPRESS__
218 |
219 | export default new Vuex.Store({
220 | state,
221 | getters,
222 | mutations,
223 | actions
224 | })
225 | ````
226 | *More advanced implementations may want to decouple this localized store from the Vuex store, but I think it decreases the initial complexity.*
227 |
228 | ### Requesting Data
229 |
230 | #### Making WP REST API Requests
231 |
232 | You will not see any WP REST API requests within the components of the theme. Instead, Vuex actions are dispatched signalling a need for asynchronous data. If the data is not available in the store, only then is a request made. When the request is returned the response data is added to the store.
233 |
234 | #### Request Caching
235 |
236 | Every time there is a request for a list of items, a request object is generated once the response is received.
237 | ````js
238 | // Example request object
239 | {
240 | data: [ 121, 221, 83, 4, 23, 76 ], // ids of items
241 | params: { page: 1, per_page: 6 },
242 | total: 21,
243 | totalPages: 4
244 | }
245 | ````
246 | This object is added to the store and next time a list of items of the same type and params are requested, the data key is used to create the response instead of querying the server.
247 |
248 | Note that these request objects are not created for requests for a single resource by its identifier because checking the store for them before making a request is trivial.
249 |
250 | ### Actions Api Reference
251 |
252 | #### Request an item of type by its slug
253 |
254 | ````js
255 | this.$store.dispatch('getSingleBySlug', { type, slug, showLoading })
256 | ````
257 | - `type` is the key in the store and the endpoint for the resource
258 | - `string`
259 | - required
260 | - `slug` is the alphanumeric identifier for the resource
261 | - `string`
262 | - required
263 | - `showLoading` indicates whether a loading indicator should be shown
264 | - `boolean`
265 | - default: `false`
266 |
267 | ##### Example
268 | ```` js
269 | // request a page with slug 'about' and show loading indicator
270 | this.$store.dispatch('getSingleBySlug', { type: 'pages', slug: 'about', showLoading: true })
271 | ````
272 |
273 | #### Request an item of type by its id
274 |
275 | ````js
276 | this.$store.dispatch('getSingleById', { type, id, batch })
277 | ````
278 | - `type` is the key in the store and the endpoint for the resource
279 | - `string`
280 | - required
281 | - `id` is the numeric identifier for the resource
282 | - `number`
283 | - required
284 | - `batch` indicates whether a short delay will be added before making the request. During this delay any requests with duplicate ids are ignored and ids of the same type are consolidated into a single request using the `include` WP REST API argument.
285 | - `boolean`
286 | - default: `false`
287 |
288 | *View the [theme demo](http://vue-wordpress.com), open the Network panel of your browser, and navigate to a posts feed to see the batch feature in action.*
289 |
290 | ##### Examples
291 | ```` js
292 | // request a tag with an id of 13 with batching
293 | this.$store.dispatch('getSingleById', { type: 'tags', id: 13, batch: true })
294 | // request a tag with an id of 21 with batching
295 | this.$store.dispatch('getSingleById', { type: 'tags', id: 21, batch: true })
296 |
297 | // Even if these are called from different components or instances of the same component, the batched request would look like /wp/v2/tags/?include[]=13&include[]=21&per_page=100
298 | ````
299 |
300 | #### Request a list of items
301 |
302 | ````js
303 | this.$store.dispatch('getItems', { type, params, showLoading })
304 | ````
305 | - `type` is the key in the store and the endpoint for the resource
306 | - `string`
307 | - required
308 | - `params` are the parameters to use for the request
309 | - `Object`
310 | - required
311 | - `showLoading` indicates whether a loading indicator should be shown
312 | - `boolean`
313 | - default: `false`
314 |
315 | ##### Example
316 | ````js
317 | // request the first page of the most recent posts limited to 10 posts per page
318 | this.$store.dispatch('getItems', { type: 'posts', params: [ page: 1, per_page: 10, orderby: 'date', order: 'desc' ] })
319 | ````
320 |
321 | ### Getters Api Reference
322 |
323 | You'll notice the arguments for the getters are a subset of their corresponding action arguments. This is because the actions use the getters themeselves to make sure the data is not already in the store before making a request.
324 |
325 | #### Get an item of type by slug
326 |
327 | ````js
328 | this.$store.getters.singleBySlug({ type, slug })
329 | ````
330 |
331 | #### Get an item of type by id
332 |
333 | ````js
334 | this.$store.getters.singleById({ type, id })
335 | ````
336 |
337 | #### Get a list of items
338 |
339 | ````js
340 | this.$store.getters.requestedItems({ type, params })
341 | ````
342 |
343 |
344 | ## SEO and Server Rendered Content
345 |
346 | ### How It Works
347 |
348 | What enables SEO and server rendered content with this theme is the routing. The Vue app routing mirrors that of how Wordpress resolves query strings to templates using the [Template Hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/). So, on the server side, you know exactly what data the app will need when it renders at a specific location. The problem then becomes how to render the app with that data. Technically, the WP loop and template functions could produce output for crawlers, but it would be unusable for the app. Instead, the REST API Data Localizer is used to simulate the relevant GET requests internally corresponding to the WP template loaded, and localize that response data for the app on render.
349 |
350 |
351 | ### The Three Basic Approaches
352 |
353 | Each approach provides either explicit setup or specific examples and includes the php knowledge required to implement.
354 |
355 | #### Pseudo Headless
356 |
357 | *Minimal to no php knowledge required*
358 |
359 | With this implementation, all you need is an index.php file that renders the element the app will mount on. Add your ``, `
`, ``, and `` tags, and call `wp_head()` and `wp_footer()`. These calls ensure Wordpress still manages ``, adds ``, and enqueues scripts and stylesheets as configured.
360 |
361 | ##### Example index.php
362 | ````html
363 |
364 | >
365 |
366 |
367 |
368 |
369 |
370 |
371 |