php - 更改/重组 Wordpress REST API 的输出以包含更多数据
问题描述
我想将 Wordpress 用作我的单页 React 应用程序 (+axios) 的无头 CMS。该网站是一种投资组合,因此作为画廊附加到每个帖子的照片对我来说是最重要的。
WP REST API 返回所有必要的数据,但图像链接仅在向 [ .../wp-json/wp/v2/media?parent=X ] 发送新请求后可用。我想对其进行优化并自动将所有图像 URL 附加到常规输出中,这样我就可以获得一个复杂的响应。
我相信可以操纵 API 响应,但是我不太喜欢 Wordpress。如果提供任何提示和链接来实现这一点,我将不胜感激。提前致谢。
解决方案
这是为帖子路线返回特色图片
示例帖子路由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' );
使用返回的特色图片发布路线请求
推荐阅读
- python - 如何使用 python 在 xlsx 文件中查找特定关键字?
- autocomplete - 为 MudBlazor 自动完成提供来自服务的内容
- r - 将重叠间隔与 lubridate 相结合
- emacs - 如何配置 org 模式来评估 J 代码块?
- pop3 - 邮件服务器如何在没有明文用户密码的情况下实现 POP3/APOP?
- python-3.x - 如何创建一个返回给定纬度和经度栅格值的函数?
- python - 无法在导入的图像上绘制形状
- iis - 使用 IIS 和反向代理为 SSL 设置 SonarQube 会引发 502 错误
- r - 如何将 2 列的所有组合放入 R 中的 1 个数据框中?
- c++ - “while (!(cin >> x) || (cin.peek() != '\n') || x <= 0)”在 C++ 上的含义