【发布时间】:2020-02-26 07:06:57
【问题描述】:
我正在尝试通过编辑 functions.php 文件将一些字段添加到 REST API。由于我对 WP 没有太多经验,因此我研究了如何操作并想出了以下代码:
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;
}
问题在于,当我按类别获取帖子列表时,这将返回所有帖子中的所有图像,而不仅仅是与其相关的图像。我怎样才能使每个帖子只返回其相关图像?
【问题讨论】:
标签: wordpress wordpress-rest-api