How can I get a list of posts for a category with WP-API?

Should be easy, but didnt find it in the WP-API docs.

Related posts

Leave a Reply

5 comments

  1. For category name, two filters should be added like this:

    add_filter( "rest_post_query", function( $args, $request){
                    if ( isset( $request['category_name']) && !empty($request['category_name'] ) ) {
                        $args['category_name'] = $request['category_name'];
                    }
                    return $args;
                }, 10, 2);
    
    
    add_filter( "rest_post_collection_params", function($query_params, $post_type){
                    $query_params[ 'category_name' ] = array(           
                        'description' => __( 'Category name.' ),
                        'type'        => 'string',
                        'readonly'    => true,
                    );
                    return $query_params;
                }, 10, 2);
    
  2. This code is working for me

    Add to your function.php

    function rest_filter_by_custom_taxonomy( $args, $request ) {
    
    if ( isset($request['category_slug']) )
    {
        $category_slug = sanitize_text_field($request['category_slug']);
        $args['tax_query'] = [
            [
                'taxonomy' => 'category',
                'field'    => 'slug',
                'terms'    => $category_slug,
            ]
        ];
    }
    
    return $args;
    
     }
     add_filter('rest_post_query', 'rest_filter_by_custom_taxonomy', 10, 3);
    

    EX: /wp-json/wp/v2/posts?category_slug=news