我正在开发一个应用程序,并通过WP的Api检索帖子列表,但我需要一个参数来检索只有视频的帖子,这是一个名为meta_video的自定义字段
示例:https://meusite.com/wp-json/wp/v2/posts?categories=1检索类别1中的所有帖子
示例2:通过URL传递参数并检索所有包含视频iframe的帖子的https://meusite.com/wp-json/wp/v2/posts?meta_video=true。
我怎么能这样做呢?
发布于 2020-01-06 21:51:49
我认为最好的解决方案可能是创建一个新的API端点( https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/ )。
add_action( 'rest_api_init', 'my_rest_post_with_videos_endpoint' );
function my_rest_post_with_videos_endpoint() {
register_rest_route( 'wp/v2', 'post/with-videos', array(
'methods' => 'POST',
'callback' => 'my_post_with_videos',
) );
}在这个端点中,只返回一个元查询,您可以在其中获得该元查询的所有帖子:示例查询
function my_post_with_videos( $request = null ) {
$args = array(
'post_type' => 'post',
'meta_query' = array(
array(
'key' => 'meta_video',
'compare' => 'EXISTS',
),
);
$response = new WP_Query( $args );
return new WP_REST_Response( $response, 200 );
}请记住,这是一个非常基本的示例,没有验证或错误检查。
https://stackoverflow.com/questions/59613186
复制相似问题