我已通过以下代码注册向WordPress REST API编写了自定义终结点:
register_rest_route( 'v1/app', '/matches(?:/(?P<id>\d+))?', array(
array(
// By using this constant we ensure that when the WP_REST_Server changes, our readable endpoints will work as intended.
'methods' => WP_REST_Server::READABLE,
'callback' => 'matches_equal_get_details',
'args' => [
'appID'
],
),
) );
但是,当我添加从自定义帖子类型中解析的metabox字段appID时,似乎无法让端点执行查询。我想写点东西
domain/wp-json/v1/app/matches?appID=5b880ecbf5d3aa1e219e0e6b
,并且仅返回网址中具有匹配元值的帖子。我只设法获取了所有帖子的完整列表,但我只需要一个具有appID匹配元值的帖子作为URL中的帖子。
function matches_equal_get_details( $request ) {
$posts = get_posts( array( 'post_type' => 'sp_event', 'orderby' => 'post_date', 'post_status' => 'publish' , 'numberposts' => -1 ) );
if ( empty( $posts ) ) {
return null;
}
//var_dump($posts);
foreach ($posts as $post) :
setup_postdata( $post );
if( $request == get_post_meta( $post->ID, 'tsl_appID_link_meta_value_key', true ) ) {
//Get attachment images
$images = get_attached_media('image', $post->ID);
$imagesList = [];
foreach ($images as $image) {
$imagesList[] .= wp_get_attachment_image_src($image->ID,'full')[0];
}
$details[] = array(
'ID' => $post->ID,
'appID' => get_post_meta( $post->ID, 'tsl_appID_link_meta_value_key', true ),
'match' => $post->post_title,
'MediaImages' => $imagesList,
'MatchDay' => get_post_meta( $post->ID, 'sp_day', true )
);
}
endforeach;
wp_reset_postdata();
return rest_ensure_response( $details );
}