1

I've seen plenty of samples of using meta_query to find if the value is between a range, where the range looks something like this:

  $meta_query_args = [
    'key' => "custom_field",
    'value' => [ $_GET['start'], $_GET['end'] ],
    'compare' => 'BETWEEN',
    'type' => 'numeric',
  ];

I need to do kinda the opposite. My custom_field has the range, and I can $_GET the value I need to find if it's between that range or not. So if the value of custom_field is 4-8, and the value of $_GET['number'] is 5, it should match. Basically, I need something like this:

 $meta_query_args = [
    'key' => "custom_field", // This may be a range like 4-8, or a number like 7
    'value' => $_GET['number'], // This will be a single number, like 5
    'compare' => 'BETWEEN', // I need to figure if 5 is within the range 4-8
    'type' => 'numeric', // I will only deal with numbers.
  ];

However, as much as I've tried to find how to do this, I have failed. Any help would be appreciated.

3
  • Is there a reason the custom field has to be saved as the range? Can you use two custom fields, one for min value and one for max value? Dec 10 '19 at 1:59
  • @czerspalace unfortunately, it just makes the most sense. For context, it's a woocomerce website which sells plants. There's this thing called "Hardiness Zone" each plant belongs to. It's a way to organize plants to know where in the country they can thrive. So some plants may belong to hardiness zone 4, but some may belong to zones 4-8. We can probably change it so the field is an array of values, so 4-8 turns into 4, 5, 6, 7, 8. But it may be more troublesome. Was wondering if there's a way to do it without changing the whole of the DB (it's a big site!). Dec 10 '19 at 3:28
  • Why does saving as 4-8 make the most sense? If you have two fields you can query where $value => min field AND $value <= max field. Dec 10 '19 at 18:53

Your Answer

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

Browse other questions tagged or ask your own question.