Custom endpoint filtering post by custom taxonomies
I am trying to create a custom endpoint by custom taxonomies, I have already created another for the categories and it works well, however there is something I cannot solve with this
function get_latest_posts_by_term($request) {
$args = array(
'term' = $request['term_id']
);
$posts = get_posts($args);
if (empty($posts)) {
return new WP_Error( 'empty_term', 'There are no posts to display', array('status' = 404) );
}
$response = new WP_REST_Response($posts);
$response-set_status(200);
$data = [];
$i = 0;
foreach($posts as $post) {
$data[$i]['id'] = $post-ID;
$data[$i]['title'] = $post-post_title;
$data[$i]['excerpt'] = $post-post_excerpt;
$data[$i]['date'] = $post-post_date;
$data[$i]['content'] = $post-post_content;
$data[$i]['slug'] = $post-post_name;
$data[$i]['author'] = get_the_author_meta('display_name', $post-post_author);
$data[$i]['category'] = get_the_category( $post-ID);
$data[$i]['theme'] = get_the_terms($post-ID,'theme');
$data[$i]['Rute-geografic'] = get_the_terms($post-ID,'rute-geografice');
$data[$i]['featured_image']['thumbnail'] = get_the_post_thumbnail_url($post-ID, 'thumbnail');
$data[$i]['post_tags'] = get_the_terms($post-ID,'post_tag');
$i++;
}
return $data;
}
add_action('rest_api_init', function() {
register_rest_route( 'wl/v1', 'posts/term/(?Pterm_id\d+)',array(
'methods' = 'GET',
'callback' = 'get_latest_posts_by_term'
));
});
Topic request-filter endpoints rest-api custom-taxonomy custom-post-types Wordpress
Category Web