Wp Rest Api Custom Endpoint for page subpages

I’m tring to add a custom endpoint for a page subpages.

Parent Page ID = 151

function list_subpages( $data ) {
   $subpages = get_pages( array(
       'child_of' => $data['151'],
   ) );

   if ( empty( $subpages ) ) {
       return null;
   }

   return $subpages;
}
add_action('rest_api_init', function () {
    $version = '2';
    $namespace="wp/v" . $version;
    $base="subpagelist";
    register_rest_route($namespace, "https://wordpress.stackexchange.com/" . $base, array(
        'methods' => 'GET',
        'callback' => array($this, 'list_subpages'),
    ));
});

Getting status 500 error..

How can I fix it?

1 Answer
1

It works..

function list_subpages() {

   $data = array();
   $request = array();

   $id = 151;
   $subpages = get_pages( array( 'child_of' => $id, 'sort_column' => 'menu_order' ) );

   if ( empty( $subpages ) ) {
       return null;
   }

   foreach ($subpages as $p) {
       $data['id'] = $p->ID;
       $data['title'] = $p->post_title;
       $data['img'] = wp_get_attachment_url( get_post_thumbnail_id($p->ID) );

       $request[] = $data;
   }

   return new WP_REST_Response($request, 200);
}
add_action('rest_api_init', function () {
   $namespace="wp/v2";
   $base="hizmetler";
   register_rest_route($namespace, "https://wordpress.stackexchange.com/" . $base, array(
       'methods' => 'GET',
       'callback' => 'list_subpages',
   ));
});

Leave a Comment