A
A
Alexander Mishchenko2020-04-28 21:14:06
WordPress
Alexander Mishchenko, 2020-04-28 21:14:06

How to clear key from spaces in meta_query?

Have a request

$recent2 = new WP_Query(
    array(
      'orderby' => '',
      'showposts'=>-1,
      'meta_query' => array( 
        array(
          'key' => 'cena',
          'value' => array(2500, 2999), // matches exactly "red"
            		'compare' => 'BETWEEN'
        )));

Everything works if the price is 2500. But some users added the price with a space (2500).
How to make what was filtered correctly. Or how to massively bring all prices to 1 type.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Vorotnev, 2020-04-28
@xxxsanchosxxx

array_map will help you to apply a certain action to each element of the array, and preg_replace with a simple regular expression that will remove all whitespace characters.

<?php
// Входящие данные
$values = [2500, '2 999'];

// Очистка от пробелов
$values = array_map(static function($value) {
    return preg_replace('/\s/', '', $value);
}, $values);

// Запрос
$recent2 = new WP_Query(
    [
        'showposts' => 100, // Не используйте -1, используйте достаточно большое для ваших задач число
        'meta_query' => [
            [
                'key' => 'cena', // Не называйте данные транслитом, используйтe price
                'value' => $values,
                'compare' => 'BETWEEN'
            ]
        ]
    ]
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question