Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am using WP_Query to sorting the post by user input. The input contains meta value which is display in select type field.

Normally when there is value inserted into the form, the wp_query working fine. But how about when the user want to sorting all the posts regardless what the meta is value is?

Here is what I mean:

//this is my input form 
<select name"rating">
<option value="">Show all</option> //if user select this, show all post, regardless the rating
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
 </select> 

//here is for WP_Query
$args = array(
'post_type'=>array('listing','renting'),
'posts_per_page'=> 6,
'order' => 'DESC',
'meta_query' => array(
'relation' => 'AND',
 array(
        'key' => 'rating',
        'value' => $_GET['rating']//here is what I don't understand, what if no value in this field?is it take the value as "0"?
    ),
......
),  

As you can see, in the select form, there is a option that will show all the posts regardless the rating. How do I suppose to do so?

thanks

share|improve this question
add comment

1 Answer 1

up vote 1 down vote accepted

check if the $GET['rating'] is set ( isset($_GET['rating']) or has any value. ( !empty($_GET['rating'])

if not, build the query fecthing all post without 'meta_query'

for example:

if ( (isset($_GET['rating']) && !empty($_GET['rating']) ) {
            // restrict
   $meta[] = array((
    'key' => 'rating',
    'value' => $_GET['rating'] );

} 
if ( (isset($_GET['tax']) && !empty($_GET['tax']) ) {
    $meta[] = array((
    'key' => 'tax',
    'value' => $_GET['tax'] );

}

$args = array(
         'post_type'=>array('listing','renting'),
         'posts_per_page'=> 6,
         'order' => 'DESC',
         'meta_query' => array( 'relation' => 'AND', $meta )

     );

warning: i didn't tested the new code, so the the meta_query line might break the query if $meta is empty.

share|improve this answer
    
I also thought so,but is there better way to do so? I mean shorter code, because beside the meta field, I all so have tax_meta which I also want to have similar features. –  dev-jim Jul 28 '12 at 11:58
    
you can build intermediate parts of the query depending on the isset && !empty logic. i'll update the response with more details –  peteroak Jul 28 '12 at 12:03
    
Okay,i figure it out...thanks –  dev-jim Jul 30 '12 at 11:51
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.