Meta Query relation “AND” then set array accordingly

I’m not sure if I get you right, but if you’re trying to query by multiple meta keys where the number of meta keys varies, then below is what I am using for the same purpose.

Basically it adds meta query one after another if the corresponding input is existent.

<form action="" method="post">
  <input name="item_name" />
  <select name="item_type">
    <option value="A">Item A</option>
    <option value="B">Item B</option>
    <option value="C">Item C</option>
  </select>
  <select name="company">
    <option value="D">Company D</option>
    <option value="E">Company E</option>
    <option value="F">Company F</option>
  </select>
  <input type="submit" name="submit" value="Submit" />
</form>

<?php
$meta_array = array();
$meta_array = array( 'relation' => 'AND' );
if( isset( $_POST['item_name'] ) ) $meta_array[] = array( 'key' => '_item_name', 'value' => $item_name, 'compare' => 'REGEXP' );
if( isset( $_POST['item_type'] ) ) $meta_array[] = array( 'key' => '_item_type', 'value' => $item_type, 'compare' => '=' );
if( isset( $_POST['company'] ) ) $meta_array[] = array( 'key' => '_item_companies', 'value' => $allowed_company, 'compare' => 'REGEXP' );

$args = array( 
        'post_type'         => 'item',
        'post_status'       => 'publish',
        'meta_query'        => $meta_array
    );

$wp_query = new WP_Query( $args );



?>

Of course the variables above need to be changed to suit your needs.

Hope this was what you were looking for.

tech