Conditional arguments WP_Query for post custom fields

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.

Read More

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 ) 
                );

Related posts

Leave a Reply

2 comments

  1. 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