【问题标题】:Change/restructure output of Wordpress REST API to include more data更改/重组 Wordpress REST API 的输出以包含更多数据
【发布时间】:2019-01-14 06:15:21
【问题描述】:
我想将 Wordpress 用作我的单页 React 应用程序的无头 CMS
(+ axios)。该网站是一种投资组合,因此作为画廊附加到每个帖子的照片对我来说是最重要的。
WP REST API 返回所有必要的数据,但图像链接仅在向 [.../wp-json/wp/v2/media?parent=X] 发送新请求后可用.我想对其进行优化并自动将所有图像 url 附加到常规输出中,这样我就可以获得一个复杂的响应。
我相信可以操纵 API 响应,但是我不太喜欢 Wordpress。如果提供任何提示和链接来实现这一点,我将不胜感激。提前致谢。
【问题讨论】:
标签:
php
wordpress
reactjs
wordpress-rest-api
【解决方案1】:
这是为帖子路线返回特色图片
示例帖子路由https://your-wp-site.com/wp-json/wp/v2/posts
function wp_featured_image( $object, $field_name, $request ) {
if( $object['featured_media'] ){
$img = wp_get_attachment_image_src(
$object['featured_media'],
'thegoodartisan-big'//default: 'thumbnail' or create customize sizes -> add_image_size( 'thegoodartisan-thumb', 220, 180, true ); //(cropped)
);
return $img[0];
}
return false;
}
function featured_media_posts_api(){
register_rest_field( array('post'),//name of post type 'post', 'page'
'thegoodartisan_featured_media',//name of field to display
array(
'get_callback' => 'wp_featured_image',
'update_callback' => null,
'schema' => null,
)
);
}
add_action('rest_api_init', 'featured_media_posts_api' );
使用返回的特色图片发布路线请求