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/

Read More

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.

Related posts

2 comments

  1. 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.

  2. In addition to Laust Deleuran’s answer (thanks Laust!), i’ve created an altered version of his script which allows you to use the embedded feature of the REST-api.

    Although this might not be ‘the cleanest’ solution, it does allow you to fully use the wp-json‘s functionality.

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

    This will output the sticky posts in the same schema as a normal /wp-json/wp/v2/posts query would respond.

Comments are closed.