如何从wp-json API中按帖子格式“标准”过滤帖子?

时间:2022-02-07 作者:Nipuna

我需要把帖子传过去wp-json 拥有"standard" 作为其格式。我一直在尝试不同的方法,比如WP_Query 像这样。

function get_blog_posts() {
    $posts = new WP_Query( array(
        \'post_type\' => \'post\',
        \'posts_per_page\' => 4,
        \'tax_query\' => array(
            array(
                \'taxonomy\' => \'post_format\',
                \'operator\' => \'NOT EXISTS\',
            ),
        ),
    ));

    if (empty($posts)) {
        return null;
    }

    return $posts->posts;
}
add_action( \'rest_api_init\', function () {
    register_rest_route( \'unicorn/v1\', \'/blog-posts\', array(
        \'methods\' => \'GET\',
        \'callback\' => \'get_blog_posts\',
    ));
});
让他们通过GET /wp-json/unicorm/v1/blog-posts

它会返回我想要的帖子,但我需要它来让它们通过wp-json 标准API提供的所有其他信息(如jetpack_featured_media_url). 任何帮助都将不胜感激。

1 个回复
最合适的回答,由SO网友:Nipuna 整理而成

这可能不是最好的答案,但就目前而言,我已经能够使用前面提到的WP\\U查询的结果,通过WP\\U REST\\U请求再次查询,获得我想要的结果。所以完整的解决方案如下所示。

function get_blog_posts() {
    $posts = new WP_Query( array(
        \'post_type\' => \'post\',
        \'posts_per_page\' => 4,
        \'tax_query\' => array(
            array(
                \'taxonomy\' => \'post_format\',
                \'operator\' => \'NOT EXISTS\',
            ),
        ),
    ));
    
    $ids = [];
    
    foreach($posts->posts as $post){
        $ids[] = $post->ID;
    }
    $include = implode(",", $ids);
    
    $request = new WP_REST_Request( \'GET\', \'/wp/v2/posts\' );
    $request->set_query_params( [ \'include\' => $include ] ); // because WP_REST_Request doesn\'t allow you to have query parameters inline.
    $response = rest_do_request( $request );
    
    $response = $response->get_data(); // You may handle errors too

    if (empty($response)) {
        return null;
    }

    return $response;
}

add_action( \'rest_api_init\', function () {
    register_rest_route( \'unicorn/v1\', \'/blog_posts\', array(
        \'methods\' => \'GET\',
        \'callback\' => \'get_blog_posts\',
    ));
});