2

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

1 Answer 1

4

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.

2
  • 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, 2012 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
    – pcarvalho
    Jul 28, 2012 at 12:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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