1

I have a text that is submitted to search on a wordpress site: "text123". From this text I would like to extract a number consisting of 3 digits (123) and search for the post that has a 'key' = 'offer' and a value of this key equals to the 3 digit number extracted from the search text (in this case '123'). I cannot get it to work with the following code:

preg_match('/[0-9]{3}/',get_query_var( 's' ), $matches);
$off = $matches[0];

$meta_query = 
    array(
        'key' => 'offer',
        'value' => $off,
        'compare' => '='
    );
$query->set( 'meta_query', $meta_query );

The $query seems to be just ignoring the 'meta_query' and returns the results that contain the whole searched text ("text123").

When I assign a value like this:

$query->set('posts_per_page', '4');

it works fine and only 4 posts are displayed in search results. But with meta_query it has no effect on $query what so ever.

Does someone know what is wrong?

  • If you're inside the pre_get_posts filter, can you not use $query->get('s') instead of get_query_var? I'm assuming this is inside that filter. Also keep in mind that your offer post meta should be stored as a taxonomy named offers instead, it would be significantly faster in every way – Tom J Nowell Jan 6 at 18:46
1

Meta query should be an array of arrays (every array contains one condition).

So instead of

$meta_query = 
    array(
        'key' => 'offer',
        'value' => $off,
        'compare' => '='
    );
$query->set( 'meta_query', $meta_query );

There should be

$meta_query = array(
    array(
        'key' => 'offer',
        'value' => $off,
        'compare' => '='
    )
);
$query->set( 'meta_query', $meta_query );

PS. It would be a good idea to check if preg_match returns true - if there is no match, your code won’t make much sense, I guess ;)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.