0

I have a form on a page that search property with a location field and I used the following meta query to process the search;

$location = preg_replace('/^-|-$|[^-a-zA-Z0-9]/', '', $_GET['location']); 

    $meta_query = array( 'relation' => 'AND' );
    if($location) {
        $meta_query[] = array(
            'relation' => 'OR',
            array(
                'key' => 'property_country',
                'value' => $location,
                'compare' => 'LIKE'
            ),
            array(
                'key' => 'property_city',
                'value' => $location,
                'compare' => 'LIKE'
            ),
            array(
                'key' => 'property_location',
                'value' => $location,
                'compare' => 'LIKE'
            )
        );
    }

However, it works fine if I search for New but returns no results if I search for New York. How can I resolve this? Is there a way to add a wildcard before and after the $location? I tried adding '*'.$location.'*' but that did nothing.

2

Have you var_dumped $location?

WP_Query's meta_query uses the class WP_Meta_Query, which automatically appends and prepends '%' to any string passed to it:

// From wp-includes/class-wp-meta-query.php:610 
switch ( $meta_compare ) {
            // ...
            case 'LIKE' :
            case 'NOT LIKE' :
                $meta_value = '%' . $wpdb->esc_like( $meta_value ) . '%';
                $where = $wpdb->prepare( '%s', $meta_value );
                break;
            // ...
}

So maybe try using (string) $location as the sql statement is prepared, and expecting a string -- that's what the %s means in the line $where = $wpdb->prepare( '%s', $meta_value );. You can cast your variable to a string like this:

$location = (string) preg_replace('/^-|-$|[^-a-zA-Z0-9]/', '', $_GET['location']);
| improve this answer | |
  • can you explain your last line a little more I don't quite get it. – Naz Jul 21 '16 at 13:03
  • @Naz I've updated my answer for clarity :) – FaCE Jul 21 '16 at 15:32
  • I tried it but no joy. – Naz Jul 21 '16 at 20:23
  • @Naz I must have misread your original question. Please see my new answer above. – FaCE Jul 22 '16 at 10:45
1

Try joining the string with wildcards:

$location = implode('%', explode($location, ' '));
| improve this answer | |

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.