3

Is it possible to return a list of posts based from the Wordpress Rest API v2 based on their schema:

For List of Schemas: http://v2.wp-api.org/reference/posts/

I want to filter by sticky field, but the same would go for the rest of the fields.

So far I have:

/wp-json/wp/v2/posts?filter[sticky]=true
/wp-json/wp/v2/posts?filter[sticky]=1

Both return the same response as the standard endpoint:

/wp-json/wp/v2/posts

I have read other material such detailing how to sort by meta or custom taxonomies but I don't believe that's the same as this.

4

2 回答 2

1

在查看文档并在 WP-API Github 存储库上查看和发布问题后,很明显filter[ignore_sticky_posts]应该切换预期的排序行为,以便始终首先(默认)或忽略(通过使用filter[ignore_sticky_posts]=true)粘性帖子。

但是,目前 WP API中存在一个错误,导致该filter[ignore_sticky_posts]标志无法使用。

现在修复它的最佳方法是创建您自己的自定义端点以获取数据库中所有粘性帖子的数据或 ID。通过查看此线程WP-API 文档中讨论的代码,我认为将以下代码添加到您的代码中functions.php应该可以解决问题:

// Sticky posts in REST - https://github.com/WP-API/WP-API/issues/2210
function get_sticky_posts() {
    $posts = get_posts(
        array(
            'post__in' => get_option('sticky_posts')
        )
    );

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

    return $posts;
}
add_action( 'rest_api_init', function () {
    register_rest_route( 'THEME_NAME/v1', '/sticky', array(
        'methods' => 'GET',
        'callback' => 'get_sticky_posts',
    ));
});

如果你GET /wp-json/THEME_NAME/v1/sticky,你应该得到一个包含所有粘性帖子的数组。

我希望这有帮助。

于 2016-02-02T01:59:39.680 回答
0

除了 Laust Deleuran 的回答(感谢 Laust!),我还创建了他的脚本的修改版本,它允许您embedded使用REST-api.

尽管这可能不是“最干净”的解决方案,但它确实允许您充分使用wp-json's 的功能。


function get_sticky_posts(WP_REST_Request $request) {

    $request['filter'] = [
        'post__in' => get_option('sticky_posts')
    ];

    $response = new WP_REST_Posts_Controller('post');
    $posts = $response->get_items($request);

    return $posts;
}

add_action( 'rest_api_init', function () {
    register_rest_route( 'THEME_NAME/v1', '/sticky', array(
        'methods' => 'GET',
        'callback' => 'get_sticky_posts',
    ));
});

这将像普通查询posts一样输出粘性。schema/wp-json/wp/v2/posts

于 2016-07-27T13:13:52.160 回答