【问题标题】:Wordpress JSON api fetch selected itemsWordpress JSON api 获取所选项目
【发布时间】:2018-02-20 23:41:52
【问题描述】:

如何仅获取帖子标题,我使用 JSON api 的 WordPress 博客的所有帖子的摘录。

目前,我正在使用https://www.example.com/wp-json/wp/v2/posts,它会返回大量数据,从而减慢整个过程。有没有可以只获取选定字段的网址?

【问题讨论】:

    标签: wordpress wordpress-rest-api


    【解决方案1】:

    您是否考虑过编写自己的 API 端点? https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/

    当你的端点变成http://example.com/wp-json/myplugin/v1/post-titles时,这样的东西可能对你有用:

       function my_awesome_func( $data ) {
         $args = array(
         'post_type' => 'post',
         );
         $query = new WP_Query( $args );
    
         $arr = array();
         while ( $query->have_posts() ) {
          $query->the_post();
          $titles = get_the_title();
          array_push($arr, $titles);
         }
         return $arr;
       }
    
       add_action( 'rest_api_init', function () {
         register_rest_route( 'myplugin/v1', '/post-titles', array(
           'methods' => 'GET',
           'callback' => 'my_awesome_func',
         ) );
       } );
    

    【讨论】:

    • 我可以在我们自己的插件中使用它吗?访问这个的确切网址是什么?
    猜你喜欢
    • 2017-09-02
    • 2020-12-12
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    相关资源
    最近更新 更多