3

I added this snippet of code to my functions.php to be able to make a request to a custom post type and filter by book_id

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

  return $args;
} );

so with that I am able to make a request to 'http://localhost:port/wp-json/wp/v2/gallery?book_id=9780061992254' gallery is a custom post type and bookd_id is one of its custom fields

the issue I am having here is after this I can't do requests to /wp-json/wp/v2/gallery without book_id anymmore and I really need to be able to do it, how can I get rid of that situation? I was looking for a way to make this param optional but I didn't find anything yet

1 Answer 1

2

It's not so difficult. All you have to do is to add a condition and check if the book_id param is passed. You can even check if this param is correct (for example if the book_id should be a number, then you can check if it is):

add_filter( 'rest_gallery_query', function( $args ) {
    if ( trim($_GET['book_id']) ) {  // check if book_id is passed and is not empty, but you can modify this condition
        $args['meta_query'] = array(
            array(
                'key'   => 'book_id',
                'value' => trim( $_GET['book_id'] ),  // <- you don't need to esc_sql this
            )
        );
    }

    return $args;
} );
2
  • sorry but it doesn't work, the book_id is still required using your answer May 25, 2018 at 13:44
  • 1
    @WagnerMoreira what do you mean when you write "it is required"? If you don't pass it or you pass an empty string as this param, then no meta_query will be added. So no - it is not required - it's optional. May 25, 2018 at 13:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.