How do I filter Child Posts by Parent Post ID for Custom Post types in WordPress REST API response?

I’d start out by checking that your request is being passed properly. I’d do that by changing this:

function custom_api_get_all_posts_callback( $request ) {

  // Initialize the array that will receive the posts' data.    

  $posts_data = array();

to this:

function custom_api_get_all_posts_callback( $request ) {

  // Initialize the array that will receive the posts' data.    

  echo "<pre>";
  print_r( $request );
  echo "</pre>";

  $posts_data = array();

… and then calling the page as you do: https://domain.com/wp-json/app/v1/answers?question=1234

Then you should be able to see your request.


It looks like that your code is returning a list of posts. But if you then add a check in the top saying (if id is specified, then return just a single post). It would look something like this:

if( $request->get_param( 'id' ) ):
  // Find that page and return just that.
endif;