user3525989 user3525989 - 4 months ago 16
JSON Question

WP API Filter By Post Schema

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.

Answer

After going through the documentation and looking and posting issues on the WP-API Github repo, it's become clear that the filter[ignore_sticky_posts] should toggle the expected sorting behaviour, so that sticky posts are either always first (default) or ignored (by using filter[ignore_sticky_posts]=true).

However, there's currently a bug in WP API that makes the filter[ignore_sticky_posts] flag unusable.

The best way to fix it now would be to 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, I think adding the following code to your functions.php should do the trick:

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

If you GET /wp-json/THEME_NAME/v1/sticky, you should get an array of all your sticky posts.

I hope this helps.