1

I'm using /wp-json/wp/v2/blocks to request all blocks on the frontend, but I just get a response of [] even though I've made a reusable block in admin.

I suspect that what I mean by block and what Wordpress 6 means are different things, but I've not found the REST API documentation helpful in this regard - perhaps I'm too deep for definitions to be provided.

Why I'm doing this

In WP6, there are reusable blocks. These seem ideal to be pulled down via AJAX so that pages can be otherwise statically cached. Perhaps there's a better way to handle FPC hole-punching but I've not found it, and with a JSON REST API this seems ideal.

1 Answer 1

1

How do I get reusable blocks via frontend REST API?

We need to be logged in as a user and additionally add the wp_rest nonce to the block rest endpoint request, either via the _wpnonce POST/GET parameter or via the X-WP-Nonce header.

See e.g. the docs for more information on the authentication.

EDIT: As pointed out in comment, to do what questioner is trying to achieve you would need to create a custom endpoint without authentication as the existing block endpoint checks permission of current user.

2
  • If you have to be logged in as a user, that's no use on the frontend. That sounds like something that would only be useful in the admin panel. Is the REST API not available for anonymous use on the frontend? If so, is there an alternative to allow static pages with dynamic elements? Jun 19, 2022 at 9:34
  • 1
    Fetching e.g. /posts doesn't require logged in users nor nonce for CSRF protection, but fetching e.g. /user/me and /blocks requires it (see .e.g the current_user_can( 'read_post', $post->ID ) permission check here within the block's rest controller). You can also create/code your own endpoints to better serve your needs or use possibly other plugins for block endpoints.
    – birgire
    Jun 19, 2022 at 15:32

Your Answer

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

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