WordPress REST API Custom Endpoint with Users and Posts

I am trying to create a new custom endpoint to list all users and their latest posts in one query.

I get an Error Message:
array_push() expects parameter 1 to be array, null

I don’t see the problem, it should be an array or what is causing this issue?

My code:

    add_action( 'rest_api_init', function () {
  register_rest_route( 'myplugin/v1', '/author', array(
      'methods'  => WP_REST_Server::READABLE,
        'callback' => 'my_custom_endpoint',

  ) );
} );

function my_custom_endpoint( WP_REST_Request $request ) {
  $users = get_users( array(

  ) );



$userQuery[] = $users;

    foreach ( $users as $key => $user ) {
             $posts_loop = get_posts( array(
                    'author' => (int)$user.data.ID
                ) );

                $add_featured_image = function( $post ) 
                    {   
                        $image_id = get_post_thumbnail_id( $post );
                          $post->thumbnail = wp_get_attachment_url( $image_id, 'large' );
                          return $post;
                        };


                $posts_processed = array_map( $add_featured_image, $posts_loop );       


        array_push($userQuery[$key], $posts_processed);

    }


  return $userQuery;
}

Read more here: WordPress REST API Custom Endpoint with Users and Posts

Leave a Reply

Your email address will not be published. Required fields are marked *