Sitemap
Francisco Gutiérrez

Francisco Gutiérrez

An web artisan too old for the hype. 📜 "I hear and I forget. I see and I remember. I do and I understand."

WP Shortcodes for Frontity

2 min readNov 22, 2020

--

Press enter or click to view image in full size

I’ve been fiddling around with Frontity this weekend. It is an easy, painless, and quick way to deliver a Single Page Application (including SSR and react rehydration) using the WordPress API.

While I was experimenting with it, I found some shortcodes on my old theme stopped working (obviously), and I wrote a little processor that could help you to:

  • Understand Frontity HTML/react processors
  • Create your own shortcodes

Our example will take a WP Gist shortcode and return a react-gist component.

Test the nodes

Frontity will render HTML, checking each node separately and turning it into React component. Let’s take a look at a WP classic shortcode:

<p>[gist id="ed8ccd58902792d009dd6cfe2b664fa2" file=gist.js]</p>

These are 2 nodes:

  • an element type using p component, with children only 👇
  • a text type, with a shortcode string as “content”

For the processor we will need to:

  • filter the node that matches our needs
  • get the props id and file from the shortcode and use it in the react-gist component

(I added some boolean sugar to the props)

packages/mars-theme/src/processors/shortcode-utils.js

The processor

Now that we have a way of detecting and extracting any shortcode, we are going to create a processor, following a wonderful explanation from the official documentation.

Get Francisco Gutiérrez’s stories in your inbox

Join Medium for free to get updates from this writer.

We look for any nodescontaining shortcode text with the name “gist”, and if the props are ok, we return a node with a React component we want.

Remember to install the react-gist npm i react-gist for this example to work

packages/mars-theme/src/processors/gist.js

Activate your processor

Now we have to activate our great processor. We import it and add it to the list.

packages/mars-theme/src/index.js

Notes

I can’t say if this is the best-way™ to parse shortcodes. The regex could potentially be better, and there might be some other improvements, like async state changes or nested shortcodes. However, I couldn’t find any simple tutorial on this, and as soon as I understood it myself, I wanted to share it with you.

--

--

Written by Francisco Gutiérrez

An web artisan too old for the hype. 📜 "I hear and I forget. I see and I remember. I do and I understand."