Search code examples
jsxwordpress-rest-apiwordpress-gutenberg

Gutenberg block get recent pages


Based on the dynamic block example for retrieving a recent posts block, I'm trying to create a block that retrieves pages.

In the php server component I changed:

$recent_posts = wp_get_recent_posts( array(
    'numberposts' => 1,
    'post_status' => 'publish',
) );

to:

 $recent_posts = get_pages( array(
    'post_type' => 'page',
    'post_status' => 'publish'
) );

and get a php error log:

Fatal error: Uncaught Error: Cannot use object of type WP_Post as array in mysite....:24

  1. render_block_latest_pages(Array, '') /mysite/wp-content/plugins/gutenberg/lib/class-wp-block-type.php:108
  2. WP_Block_Type->render(Array, '') /mysite/wp-content/plugins/gutenberg/lib/blocks.php:238
  3. do_blocks('') /mysite/wp-includes/class-wp-hook.php:286
  4. WP_Hook->apply_filters('
  5. apply_filters('the_content', '
  6. the_content() /mysite/themes/bt-sass-blank-theme/template-parts/page/content-default.php:7

I also tried a normal query and it does not work. Gutenberg works with the Wordpress REST API, not sure if there might be an issue there.


Solution

  • wp_get_recent_posts returns an array of post arrays by default, while get_pages returns and array of page objects. If you're using the linked example verbatim, then you would need to replace $post_id = $post['ID'] with $post_id = $post->ID.