Site icon Hip-Hop Website Design and Development

Multiple nested meta queries

This has been driving me nuts for days so if anyone can provide any sort of solution that would be lifesaving.

I have a form that is querying posts (WP_Query), depending on the meta data.

Form fields are $instruments, $type, $location and $mileage.

$instruments are handled by a tax query, FYI.

I can get the form working perfectly if I ignore the milage option. E.g. user can submit the form without inputting any data and it returns all posts. On one field change, or up to three, it returns the correct posts with the following:

 'meta_query'  => array(
      // If type and location fields are filled in, change query to AND, else OR
      'relation'    =>  $type !== '' && $location !== '' ? 'AND' : 'OR',

      // If type or location fields are filled in, run the meta queries
      $type == '' ? '' : array(
        'key'    => 'type',
        'value'    => $type,
        'compare'  => '='
      ),
      $location == '' ? '' : array(
        'key'    => 'location',
        'value'    => $location,
        'compare'  => '='
      ),
    ),

Now if I want to query by selecting all fields, or a combination with milage included I get stuck. Every query I’ve tried either returns 0 or all results, obviously not what I want.

I should note that if the type, location and mileage fields are filled in by the user, the query only needs to take into account the mileage and type and not the location as a result.

So my question is how do I keep the above, whilst also running a new/extended meta query, if the user selects something from the mileage options (which currently renders the above broken).

Where and how can I add the following? If user selects 10 miles (only show 10), if user selects 25 miles (show 10 and 25), if user selects 50 miles (show all 10, 25 and 50) – all with the relation to $type and $instrument, as mileage can’t be selected otherwise.

  array(
    'key'    => '10_miles',
    'value'    => $mileage,
    'compare'  => '='
  ),
  array(
    'key'    => '25_miles',
    'value'    => $mileage,
    'compare'  => '='
  ),
  array(
    'key'    => '50_miles',
    'value'    => $mileage,
    'compare'  => '='
  ),