WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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>

//here is for WP_Query
$args = array(
'posts_per_page'=> 6,
'order' => 'DESC',
'meta_query' => array(
'relation' => 'AND',
        '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?


share|improve this question
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(
         '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

Your Answer


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.