Automatically Build GatsbyJS Site When Publishing WordPress Post
With a headless WordPress site, you need a way to communicate with the front end when there is a new post. With a AJAX-only site, the API update should be sufficient, but with a Gatsby or other static site, the site has to rebuild with each update. I’ve created a quick plug-in for WordPress on my GitHub. It can also be incorporated into the functions.php
of your WordPress
So how to trigger the rebuild?
Build Hook
Netlify makes that easy with build hooks. Build hooks can be created in the site settings menu under Build & Deploy >> Continuous Deployment
.
What build hook is just a URL that you sent a POST request to in order to trigger a rebuild. And that can be easily done with JavaScript specifically with jQuery and it’s AJAX methods.
Sending the POST Request
The wp-admin
panel runs jQuery so we’ll use it to send the POST request. Below is the JavaScript code that sends the POST request.
jQuery.ajax({ type: "POST", url: 'https://api.netlify.com/build_hooks/[site specific code]', success: function(d) { console.log(d) } })
Trigger From WordPress
We have code to fire off the POST request, but we also have to attach it to an action. There are a few different ways to do this, the simplest way I found was to attach the POST request to the action of pushing the publish button or the update button. We can do that by putting an event listener on those buttons. The code below does two additional things to the initial AJAX snippet of code.
- It attaches the POST request to the #publish and #original_publish buttons, which are publish and updates buttons.
- It also limits the event listener to only the
post.php
page.
jQuery(document).ready(function() { //enables only on a normal post page if (adminpage == 'post-php') { //event handler for clicking the link button jQuery('#publish, #original_publish').on('click', function(e) { jQuery.ajax({ type: "POST", url: 'https://api.netlify.com/build_hooks/[site specific code]', success: function(d) { console.log(d) } }) }) } })
Include the JavaScript in Your WordPress CMS
The final step is to include this JavaScript into the JavaScript files that WordPress runs. We can do that with the admin_enqueue_scripts
WordPress action hook.
function wordpress_netlify_enqueue($hook) { if ( 'post.php' != $hook && 'post-new.php' != $hook ) { return; } wp_enqueue_script( 'wordpress-netlify-hook', plugin_dir_url( __FILE__ ) . '/wordpress-netlify-hook.js' ); } //enques the scripts from wordpress_netlify_enqueue add_action( 'admin_enqueue_scripts', 'wordpress_netlify_enqueue' );
This takes the JavaScript file and attaches to the post.php
and post-new.php
pages, so that the script runs when the page loads.