Rebuild Netlify on Headless WordPress Post Publish

June 02, 2019 - posted by Josh Smith

Part of the increased complexity of a headless site is queuing the rebuild process. Since I use Netlify to host my frontend and WordPress to write my posts, this process is actually fairly simple. First, I’ll explain what’s going on.

Headless Loses Some of the Brains

Going headless certainly has great advantages like phenomenal performance. But there are costs too. I love WordPress and I built my site with a headless WordPress and to that end, I lost some of the brains of WordPress. Specifically, I lost the ability to write a post, hit publish, and see my post appear on my site. Things are that simple anymore, and it’s the cost of incredible performance. Here’s what I did to fix it.

Since my site is built with Gatsby and hosted on Netlify, there are a couple of points to mention beforehand.

Gatsby is basically a type of static site generator, it’s way more but for this purpose just go with me. Gatsby takes a pile of data and created posts and pages from that pile. To do that, Gatsby has to be rebuilt each time the data changes. My Gatsby site is hosted on Netlify and I can log into my Netlify dashboard and click the Rebuild button to regenerate my site to pull in the new data. Once the site has been rebuilt the new data will appear as new pages or posts or image or whatever. Netlify knows we’ll want to automate that so they provided a sweet method to do that; webhooks.

Basically, a webhook is a way for me to send a request to a URL with a message attached. When that URL is hit it triggers something on the server to happen. Specifically, I want the server to rebuild my site. Since I use WordPress this is easy with the publish_post hook.

When I hit the save button, I want to send a message to Netlify to rebuild my site, because there is new data available.

WordPress Publish Post Hook in Action with Netlify Webhook

 * Send a request to build the site once a post is published

function deploy_on_publish() {
   wp_remote_post( '', '' );

add_action( 'publish_post', 'deploy_on_publish' );

So when I hit the Publish button, my WordPress site saves the post to my database, but it also sends a POST request to Netlify. On that POST request is my URL to trigger my site to rebuild. So simple.

You can find your Netlify Build Hook by logging into your Netlify dashboard. Navigate to your site’s settings, then Build & Depl0y settings. Then scroll down to Build Hooks section.

© 2019 All Rights Reserved

Designed by Josh at Efficiency of Movement