[REST API] feature media missing in posts array
MoOx opened this issue · 2 comments
Hi,
First, thanks for this plugin. I would like to use it for an app using wordpress as a backend.
I am currently trying it and I miss currently one thing from the results I get with /wp-json/related-posts-by-taxonomy/v1/posts/{ID}
: the featured media. Handy to display a thumb with the name :)
I didn't looked at the codebase yet, but would you be open to accept an improvement with it?
While I am at it, would you be interested to offers results from the API more like WP v2 posts listing api? Currently results from this plugin have a different json format than /wp-json/wp/v2/posts
.
For anyone interested in related posts via json api similar to wp api posts results format, here is my trick: I use "rendered" field from this plugin to render json that looks like wp "native" format.
in functions.php
// enable "Related Posts by Taxonomy" rest api
add_filter( 'related_posts_by_taxonomy_wp_rest_api', '__return_true' );
add_filter( 'related_posts_by_taxonomy_template', 'rpbt_json_format_template', 10, 3 );
function rpbt_json_format_template( $template, $type, $format ) {
if ( isset( $format ) && ( 'json' === $format ) ) {
return 'related-posts-json.php';
}
return $template;
}
add_action( 'wp_loaded', 'rpbt_json_format', 11 );
function rpbt_json_format() {
if ( !class_exists( 'Related_Posts_By_Taxonomy_Defaults' ) ) {
return;
}
$defaults = Related_Posts_By_Taxonomy_Defaults::get_instance();
$defaults->formats['json'] = __( 'WP REST JSON POSTS' );
}
Then in {your theme}/related-post-plugin/related-posts-json.php
<?php
if ($related_posts) {
$result = array();
$request = new WP_REST_Request('_GET', '', "_embed"); /* not sure that "_embed" helps */
$postController = new WP_REST_Posts_Controller("post");
global $wp_rest_server;
foreach ( $related_posts as $post ) {
setup_postdata($post);
$data = $postController->prepare_item_for_response($post, $request);
$result[] = $postController->prepare_response_for_collection($data);
}
$response = rest_ensure_response($result);
echo wp_json_encode($wp_rest_server->response_to_data($response, true));
}
else {
echo "[]";
}
?>
Now call URL: {YOUR WEBSITE}/wp-json/related-posts-by-taxonomy/v1/posts/{ID}?format=json&title=&before_shortcode=&after_shortcode=
and just use JSON.parse()
on the result fetched (rendered
field).
Hi @MoOx
I'm sorry I didn't respond. Glad you found a solution. Just to let you know I'm closing this issue