Nirmal Ram
Nirmal Ram

Reputation: 48

Wordpress:Filter search results by custom fields

I want to filter the search results by custom fields

i have a custom field cp_city and i want the that the users filter their result by city so i added a city drop down beside the searchbox and change the query to alter the results but for some reasons it isn't working.

Here is what i tried

            <?php
        $city = isset($_GET['city']) ? trim($_GET['city']) : '';
        $s = $_GET['s'];

        $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
        query_posts( array('s' => $s, 'scat' => $scat, 'post_type' => 'ads', 'ignore_sticky_posts' => 1, 'meta_key' => 'cp_state', 'meta_value' => $city, 'meta_compare' => 'LIKE', 'paged' => $paged, 'orderby' => 'rand') );
        ?>

I also tried

function SearchFilter($query) {
if ($query->is_search) {
    $query->set('meta_key','cp_state');
$query->set('meta_value','london');
}
return $query;
}

add_filter('pre_get_posts','SearchFilter');

But both of the tries failed. Can anyone figure out the correct solution.

Upvotes: 1

Views: 2792

Answers (1)

Amos N.
Amos N.

Reputation: 637

You should do it like this:

<?php
$city = isset($_GET['city']) ? trim($_GET['city']) : '';
$s = $_GET['s'];

$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
query_posts( 
    array(
        's' => $s, 
        'scat' => $scat, 
        'post_type' => 'ads', 
        'ignore_sticky_posts' => 1, 
        'meta_query' = > array(
            'key' => 'cp_city', 
            'value' => $city, 
            'compare' => 'LIKE' 
        ),
        'paged' => $paged, 
        'orderby' => 'rand') 
    );

?>

Upvotes: 1

Related Questions