WP API 按 Post 模式过滤

WP API Filter By Post Schema

是否有可能 return 基于 Wordpress Rest API v2 的帖子列表基于他们的模式:

对于架构列表: http://v2.wp-api.org/reference/posts/

我想按置顶字段过滤,但其他字段也一样。

到目前为止我有:

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

两者 return 与标准端点的响应相同:

/wp-json/wp/v2/posts

我读过其他 material 详细说明如何按 meta or custom taxonomies 排序,但我不认为这与此相同。

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

但是,currently a bug in WP API 使得 filter[ignore_sticky_posts] 标志无法使用。

现在修复它的最佳方法是 create you own custom endpoint to get the data or IDs of all the sticky posts in your database. By looking at the code discussed in this thread and in the WP-API documentation,我认为将以下代码添加到 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,你应该得到一个包含所有置顶帖子的数组。

希望对您有所帮助。

除了 Laust Deleuran 的回答(感谢 Laust!),我还创建了他的脚本的修改版本,允许您使用 REST-apiembedded 功能。

虽然这可能不是 'the cleanest' 解决方案,但它确实允许您充分利用 wp-json 的功能。


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',
    ));
});

这将在与正常 /wp-json/wp/v2/posts 查询响应相同的 schema 中输出粘性 posts