0

Let's say you want to dynamically inject 10 extra posts to a WordPress site's homepage blog roll. The 10 new posts are added after some user interaction. So for this example let's pretend the JSON response of the user interaction is identical to the results of this call:

GET /wp-json/wp/v2/posts?s=awesome

What is the ideal way to add the results into the homepage, but ensuring the new posts use the same HTML as the existing ones?

In my mind it seems like the options are currently:

1- Write a loop in Javascript and write the correct html for the posts inside the loop. But that would complicate things like translations and I already have loop templates in PHP, so feels like duplicating code.

2- Writing a custom endpoint. But from what I understand I'd need to write a new WP_Query() with the search parameters, and then return all the html in a single variable (so no get_template_part() and duplicating code again).

3- A hacky idea I had was to add a hidden empty skeleton of the html of a post somewhere on the site on page load. Then when the time comes, in Javascript run a loop and clone the skeleton each time to inject the relevant post data from the JSON. But this feels nasty to me.

Is there a better way? Or am I misunderstanding a basic concept of the WP REST API?

2
  • Can you use new javascript es6 features in your setup?
    – Jorge
    Nov 30, 2016 at 11:03
  • I'm afraid not, it's a standard WordPress theme with a single standard .js file.
    – capvidel
    Nov 30, 2016 at 12:06

1 Answer 1

2
+50

Your idea #3 sounds a lot like using a templating language like Handlebars, and isn't all that hacky necessarily.

You'd "hide" your HTML template in a script tag and then use Javascript to render it with the data that comes from your Ajax call. See the examples here for a basic idea: http://handlebarsjs.com/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.