I'm using the REST API to access WordPress data and publish it on a custom frontend as part of an integration.

This works great because the shortcodes are parsed and rendered by WordPress so the content field returned from the API includes the shortcode HTML rather than the shortcode itself.

The issue is that most of the shortcodes require some JS and CSS to properly function, but this is not included by the REST API. An example of this would be a form plugin that usually includes some CSS to style the form and some JS to validate and process the form.

The system doesn't use a fixed set of plugins so I can't just hardcode references to the assets.

My question is this: how can I get the required assets (js, css) for a post when accessing it via the REST API?

I have 2 ideas and I'm not confident or proud of either:

  1. Send a separate HTTP request to the post view URL and try to extract the content directly from the HTML. This will be slow and prone to error.

  2. Build a REST API feature that can be given a post ID and return the required assets. Again, this is another HTTP request and I woudl like to avoid that if possible.

Also, I'm aware of the cross domain XML issues I may face when these plugins try to make AJAX requests, but I will get around this using Access-Control-Allow-Origin on the WP server.

  • The point of a REST API is usually to get content without this stuff. That's why it's often called "headless". You're essentially taking the idea of headless WordPress and sewing the head back on. The proper way to handle this would normally be to ensure that any assets you need are already part of your front end. #2 is going to be difficult because a REST API endpoint will not enqueue scripts, meaning you'd need to manually trigger the action so your theme/plugins enqueue their scripts, but then any scripts or styles that are enqueued conditionally won't be enqueued properly. Oct 1 at 9:26
  • To get around that you'd need to start doing things in your endpoint to trick the theme and plugins into thinking it's a normal front-end request, and at that point you're just rebuilding the front end anyway, and basically doing #1 the hard way. WordPress just doesn't manage assets in away that supports this kind of use case. Can you elaborate on the nature of this integration? It seems unusual to me to be consuming content via the REST API that is so dependent on external scripts and styles. Oct 1 at 9:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.