英文:
Customize WordPress API Query
问题
我正在开发一个应用程序,并通过WP的API检索帖子列表,但我需要一个参数来仅检索具有视频的帖子,该参数称为meta_video。
示例:https://meusite.com/wp-json/wp/v2/posts?categories=1 检索所有类别1的帖子
示例2:https://meusite.com/wp-json/wp/v2/posts?meta_video=true 通过URL传递参数并检索所有包含视频iframe的帖子。
我该如何做到这一点?
英文:
I'm developing an app and retrieving a list of posts via WP's Api, but I needed a parameter to retrieve only posts that have video, which is a custom field called meta_video
Example: https://meusite.com/wp-json/wp/v2/posts?categories=1 retrieves all posts from category 1
Example 2: https://meusite.com/wp-json/wp/v2/posts?meta_video=true to pass a parameter by the URL and retrieve all posts that have a video iframe.
How could I do this?
答案1
得分: 2
I think the best solution might be creating a new API endpoint ( 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',
) );
}
And in this endpoint just return a meta query where you get all the posts with that meta: example query
```php
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 );
}
Please keep in mind this is a very basic example with no validations or error checks.
英文:
I think the best solution might be creating a new API endpoint ( 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',
) );
}
And in this endpoint just return a meta query where you get all the posts with that meta: example query
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 );
}
Please keep in mind this is a very basic example with no validations or error checks.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论