【发布时间】:2019-12-03 10:36:58
【问题描述】:
我为我的 Wordpress 插件中的自定义表中的特定数据创建了一个自定义端点。它使用getHelpers() 函数从表中获取所有数据。之后它将被一些用户数据合并。我想将 profile_image 添加为响应的链接,以便我们可以使用 embed 参数获取它。
将链接添加到响应的最佳方式是什么?我知道$response->add_link() 函数,但这会将其添加到响应中,而不是添加到每个贡献者中。
我尝试将链接添加为数组,但这不会对 the _embed 参数做出反应。
这是我的自定义端点代码:
class VEMS_Rest_Contributors extends WP_REST_Controller {
protected $namespace = 'vems/v2';
protected $rest_base = 'contributors';
/**
* Register the routes for coupons.
*/
public function register_routes() {
register_rest_route( $this->namespace, '/' . $this->rest_base, array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_items' ),
'args' => $this->get_collection_params(),
) );
}
public function get_items( WP_REST_Request $request ) {
$project_id = $request->get_param( 'project_id' );
$contributors = array();
if( !empty($project_id) ) {
$project = new VEMS_Project( $request['project_id'] );
$helpers = $project->getHelpers();
foreach($helpers as $helper) {
$contributor = array();
if( !empty($helper->contributor_id) ) {
$user = get_user_by( 'ID', $helper->contributor_id );
$user_meta = get_user_meta( $helper->contributor_id );
$contributor['ID'] = $helper->contributor_id;
$contributor['user_nicename'] = $user->data->display_name;
$contributor['user_profile_image'] = $user_meta['contributor_profile_image'][0];
} else {
$contributor['user_nicename'] = $helper->name;
$contributor['user_profile_image'] = $helper->image_id;
}
$contributor['item_total'] = $helper->item_total;
$contributor['checked'] = $helper->checked;
$contributor['helper_date'] = $helper->helper_date;
/*
$contributor['_links']['profile_image'] = array(
'href' => rest_url( '/wp/v2/media/' . $contributor['user_profile_image'] ),
'embeddable' => true
);
*/
$contributors[] = $contributor;
}
}
$response = rest_ensure_response( $contributors );
return $response;
}
public function get_collection_params() {
$params['project_id'] = array(
'description' => __( 'Limit result set to contributors assigned a specific project.', 'vems' ),
'type' => 'integer',
'sanitize_callback' => 'absint',
'validate_callback' => 'rest_validate_request_arg',
);
return $params;
}
}
【问题讨论】:
-
您说的是哪个 _embed 参数?我在您的代码中没有看到它。
-
默认的 Wordpress rest api 嵌入参数,它嵌入到 json 输出的链接。就像你可以对帖子做的那样: /wp-json/wp/v2/posts?_embed 有一个函数 $response->add_link( );但我无法弄清楚它如何处理多个响应。
标签: wordpress endpoint wordpress-rest-api