1

All in my case I want to get post result by Gender, Age, City etc... I am using this query. If i have any of variable like age, city, gender for that "AND" operation will perform and get only result for that variable.

Note: Consider those case also where i have no variable like city but it should work for gender & state.

My Query is

$gender = $_GET['gender'];
                $city = $_GET['city'];
                $state = $_GET['state'];

                $wp_query = new WP_Query( array( 
                    'post_type' => 'profile',
                    'meta_query' => array( 
                            'relation' => 'AND',
                            array('meta_key' => 'wpcf-gender', 'meta_value' => $_GET['gender'], 'meta_compare' => '=='),
                            array('meta_key' => 'wpcf-city', 'meta_value' => $_GET['city'], 'meta_compare' => '=='),
                            array('meta_key' => 'wpcf-state', 'meta_value' => $_GET['state'], 'meta_compare' => '==')                           
                        ),
                    'paged' => $paged ) 
                );
5

Here is a modification of your code where you can add the meta query if certain $GET keys are set.

$query_array = array('relation' => 'AND');

if(isset($_GET['gender']) && !empty($_GET['gender'])){
    $gender = $_GET['gender'];
    array_push($query_array, array('key' => 'wpcf-gender', 'value' => $gender, 'compare' => '='));
}
if(isset($_GET['city']) && !empty($_GET['city'])){
    $city = $_GET['city'];
    array_push($query_array, array('key' => 'wpcf-city', 'value' => $city, 'compare' => '='));
}

if(isset($_GET['state']) && !empty($_GET['state'])){
    $state = $_GET['state'];
    array_push($query_array, array('key' => 'wpcf-state', 'value' => $state, 'compare' => '='));
}

                $wp_query = new WP_Query( array( 
                    'post_type' => 'profile',
                    //'query' => $query_array, should be 'meta_query' => $query_array,
                    'meta_query' => $query_array,
                    'paged' => $paged ) 
                );

Reference:

array_push() : http://php.net/manual/en/function.array-push.php

2
-1
'query' => $query_array,

should be

'meta_query' => $query_array,
1
  • I don't see how this answers the question. Could you provide an explanation on how this solves their problem?
    – Howdy_McGee
    Feb 11 '15 at 15:12

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.