自定义WordPress API查询

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

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/ )

  1. add_action( 'rest_api_init', 'my_rest_post_with_videos_endpoint' );
  2. function my_rest_post_with_videos_endpoint() {
  3. register_rest_route( 'wp/v2', 'post/with-videos', array(
  4. 'methods' => 'POST',
  5. 'callback' => 'my_post_with_videos',
  6. ) );
  7. }
  8. And in this endpoint just return a meta query where you get all the posts with that meta: example query
  9. ```php
  10. function my_post_with_videos( $request = null ) {
  11. $args = array(
  12. 'post_type' => 'post',
  13. 'meta_query' => array(
  14. array(
  15. 'key' => 'meta_video',
  16. 'compare' => 'EXISTS',
  17. ),
  18. ),
  19. );
  20. $response = new WP_Query( $args );
  21. return new WP_REST_Response( $response, 200 );
  22. }

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/ )

  1. add_action( 'rest_api_init', 'my_rest_post_with_videos_endpoint' );
  2. function my_rest_post_with_videos_endpoint() {
  3. register_rest_route( 'wp/v2', 'post/with-videos', array(
  4. 'methods' => 'POST',
  5. 'callback' => 'my_post_with_videos',
  6. ) );
  7. }

And in this endpoint just return a meta query where you get all the posts with that meta: example query

  1. function my_post_with_videos( $request = null ) {
  2. $args = array(
  3. 'post_type' => 'post',
  4. 'meta_query' = array(
  5. array(
  6. 'key' => 'meta_video',
  7. 'compare' => 'EXISTS',
  8. ),
  9. );
  10. $response = new WP_Query( $args );
  11. return new WP_REST_Response( $response, 200 );
  12. }

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:

确定