Headless Theme for WordPress
Published September 18, 2018
In my previous post about editor links, I showed how WordPress can create editor links using the live site URL instead of the WordPress URL. When I created a React app for my WordPress site, I run into two issues. First, I wanted to get as much data from WordPress as possible. Second, I want visitors to only view the React app, not the WordPress install. The solution for both of these problems lies in building a WordPress theme. Huh?
WordPress Theme for a Headless App
Our headless React app still requires an activated, installed theme in our WordPress installation. Others have built similar projects, but mine serves two purposes:
- Adds support for menus, featured images, and other WordPress features
- Redirects users to the live site
I wanted my React app to behave similarly to how a typical WordPress theme behaves. For example, while most React apps use hard-coded menus, I wanted the menus to update when I manage them in WordPress. There’s no reason to edit React code just to add a menu item. Especially if the React app can get the menu structure from WordPress instead. Let’s start by looking at the files included in my Headless WordPress Theme.
Since this theme does not display any content, it should be minimal. Here is the list of files:
The style.css file only contains the required WordPress comment block. Next, let’s look at these other two files in more detail.
WordPress Feature Supports
First and foremost, the functions.php file registers support for all the WordPress features you’ll need. As an example, if you need featured images for posts and pages, you’ll need to add a statement like:
add_theme_support( 'post-thumbnails' );
Same goes for menus. Register each menu needed for your site.
This file can also be a catch-all for anything else you discover you’ll need. In future posts, I’ll talk about some of the weird WordPress quirks I corrected using the functions.php file.
We’ll also need to redirect people trying to visit our WordPress install.
Redirects in a WordPress Theme
Now that I’ve explained the simple Headless WordPress Theme, next I’ll walk through the React app itself. Creating a React app posed its own set of challenges. It requires a different way of thinking compared to building a WordPress theme.