I need to get posts through wp-json
having "standard" as their format. I've been trying different methods like using WP_Query
like this.
function get_blog_posts() {
$posts = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => 4,
'tax_query' => array(
array(
'taxonomy' => 'post_format',
'operator' => 'NOT EXISTS',
),
),
));
if (empty($posts)) {
return null;
}
return $posts->posts;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'unicorn/v1', '/blog-posts', array(
'methods' => 'GET',
'callback' => 'get_blog_posts',
));
});
Get them through
GET
/wp-json/unicorm/v1/blog-posts
It returns the posts I want but I need it to get them through wp-json
with all the other information the standard API provides (stuff like jetpack_featured_media_url
). Any help would be appreciated.
I need to get posts through wp-json
having "standard" as their format. I've been trying different methods like using WP_Query
like this.
function get_blog_posts() {
$posts = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => 4,
'tax_query' => array(
array(
'taxonomy' => 'post_format',
'operator' => 'NOT EXISTS',
),
),
));
if (empty($posts)) {
return null;
}
return $posts->posts;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'unicorn/v1', '/blog-posts', array(
'methods' => 'GET',
'callback' => 'get_blog_posts',
));
});
Get them through
GET
/wp-json/unicorm/v1/blog-posts
It returns the posts I want but I need it to get them through wp-json
with all the other information the standard API provides (stuff like jetpack_featured_media_url
). Any help would be appreciated.
1 Answer
Reset to default 1This may not be the best answer but for the time being, I've been able to get what I want through querying again via a WP_REST_Request using the results I've got from the WP_Query mentioned earlier. So the full solution looks like this.
function get_blog_posts() {
$posts = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => 4,
'tax_query' => array(
array(
'taxonomy' => 'post_format',
'operator' => 'NOT EXISTS',
),
),
));
$ids = [];
foreach($posts->posts as $post){
$ids[] = $post->ID;
}
$include = implode(",", $ids);
$request = new WP_REST_Request( 'GET', '/wp/v2/posts' );
$request->set_query_params( [ 'include' => $include ] ); // because WP_REST_Request doesn't allow you to have query parameters inline.
$response = rest_do_request( $request );
$response = $response->get_data(); // You may handle errors too
if (empty($response)) {
return null;
}
return $response;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'unicorn/v1', '/blog_posts', array(
'methods' => 'GET',
'callback' => 'get_blog_posts',
));
});