I have two Custom post types: question and answer. "Questions" are hierarchical and they are parent posts for answers - which are child posts. For every answer, there's a parent question. When someone asks a question, every answer given is correctly attributed to the same question. This has already been nicely done in the website. While I am building the APP, I can pull in all questions, but when it comes to answers, I can't seem to filter out answer by parent question.
All questions can be obtained like this: https://domain.com/wp-json/wp/v2/questions
For answers, I am using custom endpoint with this code:
add_action( 'rest_api_init', 'custom_api_get_all_posts' );
function custom_api_get_all_posts() {
register_rest_route( 'app/v1', '/answers', array(
'methods' => 'GET',
'callback' => 'custom_api_get_all_posts_callback'
));
}
function custom_api_get_all_posts_callback( $request ) {
// Initialize the array that will receive the posts' data.
$posts_data = array();
// Receive and set the page parameter from the $request for pagination purposes
$paged = $request->get_param( 'page' );
$paged = ( isset( $paged ) || ! ( empty( $paged ) ) ) ? $paged : 1;
// Get the posts using the 'post' and 'news' post types
// $avatar_url = get_avatar_url ( get_the_author_meta('ID'), $size = '50' );
$posts = get_posts( array(
'paged' => $paged,
'posts_per_page' => 10,
'post_type' => 'answer',
));
if ( is_array( $filter ) && array_key_exists( 'question', $filter ) ) {
$args['post_parent_id'] = $filter['question'];
}
// Loop through the posts and push the desired data to the array we've initialized earlier in the form of an object
foreach( $posts as $post ) {
$id = $post->ID;
$posts_data[] = (object) array(
'id' => $id,
'slug' => $post->post_name,
'type' => $post->post_type,
'title' => $post->post_title,
'content' => $post->post_content,
'question' => $post->post_parent,
);
}
return $posts_data;
}
And by this, I can get all answers with their IDs, Answer Title, Content, and Parent Question Id in GET response at https://domain.com/wp-json/app/v1/answers
QUESTION: How do I have to modify the code to be able to filter out specific answers based on question ID, something like: https://domain.com/wp-json/app/v1/answers?question=1234 where 1234 is an ID for a parent question whose answers we need to display. All suggested filter plugins have failed to work, I've tried different forms of codes for so many hours, I really appreciate your help :)
Thanks! (Both question and answer are CPTs, and I am using WP Version - 4.9.8)