简体   繁体   中英

Value meta_query Postcode Array

So I've done a fair bit of searching and I've really had no luck with this.

Essentially I have a 'postcode' custom field that I need to search for based off _GET['postcode'] in a URL query. When the page loads, It sets up arguments based off this data to create a specific WP_Query.

I've used the following to search for the postcode, which works fine to a degree:

$args = array(
    'post_type' => 'property',
    'posts_per_page' => '10',
    'meta_key'  => 'price_variable',
    'orderby'   => 'meta_value_num',
    'order'     => $_GET['sort'],
    'paged' => $paged,
    'meta_query' => array(
            array( 'key' => 'postcode', 'compare' => 'REGEXP', 'value' => $_GET['postcode'] )
    )
);

However the problem arrives whenever I have to exclude double digit postcodes. Say a user searches for HU1 but HU11, HU12 and HU13 exist too, It will bring in all of them too, case they're contained in those specifics.

This would be easier to deal with if it was just the case that the postcode was just the initial 3/4 characters, but because it's the full postcode, you have postcodes like HU13 7DS and HU7 1PQ so i can't select exact searches from it.

I've tried the relation method but the load times are ridiculous(due to having to do them for each entry from HU10-HU19) and sadly i can't seem to do a NOT REGEXP for an array of to make it faster...eg

array(
    'relation' => 'AND',
    array( 'key' => 'property_type', 'compare' => 'REGEXP', 'value' => $_GET['postcode'] ),
    array( 'key' => 'property_type', 'compare' => 'NOT REGEXP', 'value' => array('HU10', 'HU11', 'Etc'))
)

Any suggestions would be greatly appreciated it.

Also: I've also tried to create another ACF field that would limit the characters of the postcode to just 4 characters to sort this but because i'm using an xml importer for the data, it over-rides the limit, so if it's easier to create a code to create a function that creates a new stripped version of that code, how to do this would be appreciated too, as i can't find a way to do this.

Solved: So i finally managed to find a solution. I discovered that you can actually use the expression [[:space:]] to allow for the search for spaces in entries, which is extremely handy in this case as all postcodes have a space in between them.

So if i search for HU3 using a url query, it will actually search for the postcode and the spacing by just using _GET['postcode'].'[[:space:]]' as a value and REGEXP as the compare , meaning i get the exact match i need.

Hope this can be of some help to somebody in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM