Skip to content

Instantly share code, notes, and snippets.

@yoren
Last active March 3, 2016 10:30
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save yoren/f0cd9c640ecbb8b7d9e5 to your computer and use it in GitHub Desktop.
Getting Categories With Posts In A Single WP API Request
<?php
function my_rest_prepare_term( $data, $item, $request ) {
$args = array(
'tax_query' => array(
array(
'taxonomy' => $item->taxonomy,
'field' => 'slug',
'terms' => $item->slug
)
),
'posts_per_page' => 5
);
$posts = get_posts( $args );
$posts_arr = array();
foreach ( $posts as $p ) {
$posts_arr[] = array(
'ID' => $p->ID,
'title' => $p->post_title
);
}
$data->data['posts'] = $posts_arr;
return $data;
}
add_filter( 'rest_prepare_category', 'my_rest_prepare_term', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment