I’m running a standard WP_Query on a property website, and I want to find all properties that have a postcode beginning with ‘SC1’. In the meta query, doing a normal LIKE on the postcode works, but it also returns properties with postcode SC13, which isn’t what I want.

As a result, I’ve changed my meta query to be as follows:

array(
    'key'     => '_address_postcode',
    'value'   => 'SC1 ', // Notice the addition of the space
    'compare' => 'LIKE'
)

However.. it’s not working. I’ve dug deeper and it seems that WordPress is trimming the values:

https://github.com/WordPress/WordPress/blob/af69f4ab1a0b44594b1f231c183f7a533575a893/wp-includes/class-wp-meta-query.php#L597

Any idea how I can search for meta values that specifically have a space at the end? I thought of doing something like so:

array(
    'key'     => '_address_postcode',
    'value'   => 'SC1 %',// Add a space then wildcard
    'compare' => 'LIKE'
)

… but that doesn’t work. Can anyone think of a way to get around this :-S

2 Answers
2

Note sure how your structure is, but here’s one way, using RLIKE comparison and a space character class:

array(
    'key'     => '_address_postcode',
    'value'   => '^SC1[[:space:]]',    // Starts with 'SC1 '  
    'compare' => 'RLIKE'
)

Maybe you should consider adjusting the meta values, as suggested by @cybmeta?

But note that meta queries can be slow, so alternatives might be better here (e.g. as a custom taxonomy?).

Leave a Reply

Your email address will not be published. Required fields are marked *