Get templated page/post content via the WordPress API

I’ve been tasked with converting a WordPress site into a single page application so a persistent audio player can be added, while retaining its current theme. I need to do this in such a way that the theme can continue to be modified and updated using the existing custom template PHP, etc.

I’m already aware this a complex way to go about it … but that’s the given circumstances.

The rendered HTML in the WordPress JSON API output, for both pages and posts, does not include the additional HTML wrappers the templates (both default and custom) provide. I’m sure there’s a way to create a custom REST endpoint that will wrap content in their respective templates, but nowhere can I find this documented.

I’d like to avoid duplicating the template content, either in my framework code or in another PHP function someplace, since this means that other maintainers of the site who edit the PHP templates directly will have to modify it in two places. It’s OK if the existing templates have to be moved or rewritten to pass/receive their contents from somewhere else, as long as the actual template HTML and code can exist in only one place.

I’ve tried, for instance, rewriting an existing page template as a PHP function that returns a string that could then be passed to a custom endpoint, but of course page templates run inside the loop. So I tried moving the function into functions.php and calling it from the template; that creates the complexity that all the values of the_ID() and the_content() have to be passed in manually. Is there a built-in or simpler way to do this I’m not aware of?

0

Leave a Comment