I'm trying to add some fields to the REST API by editing the functions.php file. As I don't have a lot of experience with WP, i looked on how to do it and came up with the following code:
add_action( 'rest_api_init', 'add_images_to_JSON' );
function add_images_to_JSON() {
register_rest_field(
'post',
'images',
array(
'get_callback' => 'get_images_src',
'update_callback' => null,
'schema' => null,
)
);
}
function get_images_src( $object, $field_name, $request ) {
$args = array(
'posts_per_page' => -1,
'order' => 'ASC',
'orderby' => 'menu_order',
'post_mime_type' => 'image',
'post_parent' => $object->id,
'post_status' => null,
'post_type' => 'attachment',
'exclude' => get_post_thumbnail_id()
);
$attachments = get_children( $args );
$images = [];
foreach ($attachments as $attc){
$images[] = wp_get_attachment_thumb_url( $attc->ID );
}
return $images;
}
The problem is that when I get a list of posts by category, this is returning all images across all posts, not just the images related to it. How can I make it so each post returns only its related images?
Try this:
function get_images_src( $object, $field_name, $request ) {
$images = [];
$post_images = get_attached_media('image', $object->ID);
foreach($post_images as $image) {
$images[] = wp_get_attachment_image_src($image->ID,'full');
}
return $images;
}