Leonardo
Leonardo

Reputation: 29

Customize WordPress API Query

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?

Upvotes: 1

Views: 1141

Answers (1)

Yuxel Yuseinov
Yuxel Yuseinov

Reputation: 340

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.

Upvotes: 2

Related Questions