WP Shortcodes for Frontity
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
elementtype usingpcomponent, with children only 👇 - a
texttype, with a shortcode string as “content”
For the processor we will need to:
- filter the node that matches our needs
- get the props
idandfilefrom the shortcode and use it in thereact-gistcomponent
(I added some boolean sugar to the props)
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-gistfor this example to work
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.jsNotes
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.






