【问题标题】:How to use _embed parameter while fetching Posts by Category (Wordpress)?如何在按类别(Wordpress)获取帖子时使用 _embed 参数?
【发布时间】:2021-09-12 23:17:21
【问题描述】:

大家好,感谢您的宝贵时间。我是fetching all the Posts,使用categories=参数如下:

https://recipes.turboweb.online/wp-json/wp/v2/posts?categories=2

这里的类别 ID 是2。因此,它为我获取了包含 CategoryId 2 的所有帖子。但是,此请求不会获取 CommentsAuthorName 以及更多所需的数据。

我知道通过在普通查询中使用_embed,我们可以在一个查询中获取所有数据,从而节省时间和资源。这是查询的样子:

https://recipes.turboweb.online/wp-json/wp/v2/posts?_embed

这是输出:

我的问题是如何在按特定 CategoryID 获取帖子时在参数中使用 _embed ?用更简单的术语来说,我如何在下面的查询中插入 _embed 参数?

https://recipes.turboweb.online/wp-json/wp/v2/posts?categories=2

【问题讨论】:

    标签: json wordpress api


    【解决方案1】:

    在我的本地测试中,这个请求工作正常:

    http://localhost/wp-json/wp/v2/posts?categories=104&_embed

    print of the return test

    要返回 cmets,您需要在 rest_api_init 钩子中应用一个函数,如下所示:

    add_action ( 'rest_api_init' , 'add_custom_fields_to_api' ) ;
    
    function add_custom_fields_to_api () {
        register_rest_field ( 'post',
            'comments',
            [
                'get_callback' => 'cb_get_comments'
            ]
        );
    
    }
    
    function cb_get_comments( $object ) {
        // get your comments, for example with the function get_comments()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 2023-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多