How to make an meta_query optional?

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

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

Leave a Comment