Search code examples
wordpresswordpress-rest-api

cannot get all posts after added rest_post_query


I have add a rest_post_query like

add_filter( 'rest_books_query', function( $args ) {
    $args['meta_query'] = array(
        array(
            'key'   => 'title',
            'value' => esc_sql( $_GET['title'] ),
        )
    );
    return $args;

so query like wp-json/wp/v2/books?title=someTitle work, but I can't query all posts now like wp-json/wp/v2/books don't work anymore. How should I change it so it can query both? thanks


Solution

  • As I understand, you want to use the same API route to get All posts, or post by title. If so, you could simply do:

    add_filter( 'rest_books_query', function( $args ) {
        if(isset($_GET['title'])){
          //better push to meta_query array in case there is other meta_query already here
          $args['meta_query'][] = [
                'key'   => 'title',
                'value' => esc_sql( $_GET['title'] ),
          ];
        }
    
        return $args;
    });
    

    If no title parameter provided, the meta_query will not be pushed to the query parameter array.

    Note that you could also declare a new API route to do exactly what you require.