1

I am facing an issue with the meta query for my CPT. I have multiple values for a single meta key stored as a string separated with the '|' sign. I want to run a meta query that compares each value numerically and if meta has the >= to searched value it should return the result. suppose the stored meta value is "5000 | 6000 | 10000" the value search for is 4500

now it should return the above post meta as a result as it has 5000, 6000 & 10000.

here is meta query sample:

if(isset($_GET['sqft'])) {
if($_GET['sqft'] >= 1) {
    $args['meta_query'][] = array(
        'key' => 'pyre_property_size',
        'value' => $_GET['sqft'],
        'compare' => '>=',
        'type' => 'numeric'
    );
 }
}
query_posts($args);

I want to compare it numerically not using 'Like' or 'REGEX' because they both looked for the exact or similar match, not the conditional logic. What change is required in that query to get the result?

Tariq Khan
  • 43
  • 7

1 Answers1

0

After a lot of research, I found that there is no way to query a stored string and compare it as a numeric value. Here is my logical solution: The stored size as string is: "5000 | 6000 | 10000" First I explode it using the PHP explode function:

$new_size_field = get_post_meta( $post_id,'property_size', true );// $new_size_field = 5000 | 6000 | 10000 

After that converting these values into a single value using explode and store it with the new meta key named 'pyre_size2'

$single_size = (explode("|",$new_size_field));//converting into single value array
foreach( $single_size as $size ) {
        add_post_meta( $post_id, 'pyre_size2', $size, false );
}

Now the multiple values are stored for the same meta key with the same post id. You can see the add_post_meta function last parameter set to false that will enable the redundant addition of the meta with the same post_id and meta key. for more details, you can see this link.

After this, the data stored will be like this in the DB post meta table

property_size = 5000 | 6000 | 10000
pyre_size2 = 5000
pyre_size2 = 6000
pyre_size2 = 10000

Now the code with meta query for the search will be this:

if(isset($_GET['sqft'])) {
if($_GET['sqft'] >= 1) {
$args['meta_query'][] = array(
    'key' => 'pyre_size2',//the new meta key
    'value' => $_GET['sqft'],
    'compare' => '>=',
    'type' => 'numeric'
);
 }
}

query_posts($args);

In the code, you can see that I added the new meta key in an order to search the property of the size. Now the search value will go through all the sizes of that property and if the case is matched it will return that property(post) in the result.

Tariq Khan
  • 43
  • 7
  • to update the property sizes I handle it in the save_post hook. Whenever the post is updated the previous meta values of meta key 'pyre_size2' have been deleted and the new sizes are stored in the same manner using explode. – Tariq Khan May 26 '21 at 11:37