3

Usually find what I need from here without asking but seem to have run into something new, apologies if this has been answered elsewhere. I am building a site in wordpress which isn't my usual CMS but seems straight forward enough. I'm trying to get the post data using the API accessing the data at /wp-json/wp/v2/pages/24 which is great until we get to the actual content itself. The block/page content comes only as fully rendered with html. I tried using different context but this seems to either do nothing or throw a permissions error.

What I'm looking for is something along the lines of the below but cant seem to find that anywhere. Is this just not what's available or am I missing the point of this API all together? Any help would be great!

"content": {
"blocks": {
  "cover": {
    "classes": "wp-block-cover has-background-dim",
    "background-image": "https:\/\/localhost.local:8890\/wp-content\/uploads\/2020\/07\/92977310_Preview.jpeg",
    "content": "Our Range Title"
  },
  "image": {
    "classes": "wp-block-image",
    "image": "https:\/\/localhost.local:8890\/wp-content\/uploads\/2020\/07\/976545678.jpeg",
    "alt": "This is the alt for the image"
  },
  "layout": {
    "classes":  "background-green",
    "columns": 2,
    "content": [
      {
        "image": {
          "classes": "wp-block-image",
          "image": "https:\/\/localhost.local:8890\/wp-content\/uploads\/2020\/07\/976545678.jpeg",
          "alt": "This is the alt for the image"
        },
        "paragraph": {
          "classes": "",
          "content": "This is the <strong>paragraph for</strong> the left column."
        }
      },
      {
        "image": {
          "classes": "wp-block-image",
          "image": "https:\/\/localhost.local:8890\/wp-content\/uploads\/2020\/07\/976545678.jpeg",
          "alt": "This is the alt for the image"
        },
        "paragraph": {
          "classes": "",
          "content": "This is the <strong>paragraph for</strong> the right column."
        }
      }
    ]
  }
},
"protected": false

}

2 Answers 2

1

Very old question, but if anyone is stumbling around the Wordpress Rest API like I am, here's a quick snippet you can add to the functions.php file on your theme to add a blocks field on the return post/page data.

add_action(
    'rest_api_init',
    function () {

        if ( ! function_exists( 'use_block_editor_for_post_type' ) ) {
            require ABSPATH . 'wp-admin/includes/post.php';
        }

        // Surface all Gutenberg blocks in the WordPress REST API
        $post_types = get_post_types_by_support( [ 'editor' ] );
        foreach ( $post_types as $post_type ) {
            if ( use_block_editor_for_post_type( $post_type ) ) {
                register_rest_field(
                    $post_type,
                    'blocks',
                    [
                        'get_callback' => function ( array $post ) {
                            return parse_blocks( $post['content']['raw'] );
                        },
                    ]
                );
            }
        }
    }
);

Resulting in the following JSON being returned from fetching a single post:

"blocks": [
        {
            "blockName": "core\/paragraph",
            "attrs": [],
            "innerBlocks": [],
            "innerHTML": "\n<p>Here is the story content for section 1.<\/p>\n",
            "innerContent": [
                "\n<p>Here is the story content for section 1.<\/p>\n"
            ]
        },...
0

Same here, although this is old, it's useful, so here's another answer:

add_action('rest_api_init', function () {
  if (!function_exists('use_block_editor_for_post_type')) {
    require ABSPATH . 'wp-admin/includes/post.php';
  }

  // Get all post types that support the block editor
  $post_types = get_post_types_by_support(['editor']);

  foreach ($post_types as $post_type) {
    if (use_block_editor_for_post_type($post_type)) {
      register_rest_field(
        $post_type,
        'blocks',
        [
          'get_callback'    => function (array $post) {
            return parse_blocks($post['content']['raw']);
          },
          'update_callback' => function ($blocks, $post) {
            return update_post_blocks($post->ID], $blocks);
          },
          'schema' => [
            'description' => 'Gutenberg blocks as JSON',
            'type'        => 'array',
          ],
        ]
      );
    }
  }
});

/**
 * Updates a WordPress post with new Gutenberg blocks.
 *
 * @param int   $post_id The ID of the post to update.
 * @param array $blocks  The new blocks to insert.
 * @return bool|WP_Error True on success, WP_Error on failure.
 */
function update_post_blocks($post_id, $blocks)
{
  if (!current_user_can('edit_post', $post_id)) {
    return new WP_Error('rest_forbidden', __('You do not have permission to edit this post.'), ['status' => 403]);
  }

  if (!is_array($blocks)) {
    return new WP_Error('rest_invalid_param', __('Blocks must be an array.'), ['status' => 400]);
  }

  // Convert blocks back into serialized post_content
  $content = serialize_blocks($blocks);

  // Update post
  $result = wp_update_post([
    'ID'           => $post_id,
    'post_content' => $content,
  ], true);

  if (is_wp_error($result)) {
    return $result;
  }

  return true;
}

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.