When I wrote how to serve content to Hugo, I did so using something that was mostly static. You see, that code requires someone to push a new version of the Hugo site to rebuild the pages.
Now let’s be serious, who wants to do that?
The Concept
Sadly, you can’t just include a PHP file in Hugo (or any static site builder) and have it echo content. Their whole point is to be static and not change. And my problem is that I immediately ran into a week where I knew the message on the header was going to be changing daily.
Ew, right? Right. So I looked at that which I should be embracing deeply. Javascript. Or in this case, jQuery and the getJSON
call. Yes, that’s right, with jQuery you can call JSON and output it where you want.
I do not recommend doing this for full page content. This is only vaguely smart if you’re trying to output something small that loads fast and isn’t going to mess up your site if someone has javascript disabled.
The Code
<script> $.getJSON( "https://example.com/wp-json/wp/v2/pages/14363", function (json) { var content = json.content.rendered; document.querySelector('.wpcontent').innerHTML = content; }); </script> <div class="utility-bar"> <div class="wrap"> <section id="text-16" class="widget widget_text"> <div class="widget-wrap"> <div class="textwidget"> <div class="wpcontent"></div> </div> </div> </section> </div> </div>
What that code does is it grabs the JSON, sets the variable content
to the value of the content’s ‘rendered’ setting. Then using document.querySelector
, it tosses in the HTML to my class for wpcontent
and I’m done.