2

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, '/' . $base, array(
        'methods' => 'GET',
        'callback' => array($this, 'list_subpages'),
    ));
});

Getting status 500 error..

How can I fix it?

7
  • This may be not related to 500 Error but I wonder how $data['151'] giving you parent ID ?
    – Sumit
    Mar 13, 2016 at 19:29
  • I don't know. I'm not sure. I have changed codes like this (gist.github.com/sakarya/62cb0e2cabf2602775ad), but still, getting same error.
    – sakarya
    Mar 13, 2016 at 19:31
  • I just tested the above code and do not see any 500 error. Perhaps you should check for server logs. 500 error hard to debug without server logs!
    – Sumit
    Mar 13, 2016 at 19:34
  • error message is: {"code":"rest_invalid_handler","message":"G\u00fczergah i\u015fleyicisi ge\u00e7ersiz","data":{"status":500}}
    – sakarya
    Mar 13, 2016 at 19:41
  • 1
    from the provided code it looks like your class instance $this is not configured... edit try as callback just the string 'list_subpages'
    – iantsch
    Mar 13, 2016 at 22:33

1 Answer 1

2

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, '/' . $base, array(
       'methods' => 'GET',
       'callback' => 'list_subpages',
   ));
});
1
  • Lovely. Almost a copy-paste solution for me. Thank you. You could potentially comment on the code a bit for the programmers who learn.
    – Kaspi
    Apr 6, 2021 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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