自定义WordPress API查询

huangapple go评论67阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年1月6日 21:41:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613186.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定