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.

How to build taxonomy queries dyniamically?

I have this code for dynamically creating an array for color and price:

$color = $_POST['color'];
$price = $_POST['price'];

if (!empty($color)) {
    $query_color =  array(
                        'taxonomy' => 'color',
                        'field' => 'term_id',
                        'terms' => $color
        );
} else {
    $query_color = array(
                    'taxonomy' => 'color',
                    'field' => 'term_id',
                    'terms' => ''
    );
}

if (!empty($price)) {
    $query_price =  array(
                        'taxonomy' => 'price',
                        'field' => 'term_id',
                        'terms' => $color
        );
} else {
    $query_price = array(
                    'taxonomy' => 'price',
                    'field' => 'term_id',
                    'terms' => ''
    );
}

And I have this code for a query:

$args = array(
        's' => $search,
        'post_type' => array( 'post' ),
        'posts_per_page' => 99999,
        'tax_query' => array(
            'relation' => 'OR',
            $query_color,
            $query_price,
        )
);
$wp_query = new WP_Query( $args );

But, it's not working good. It always shows all posts ad not just the things from the $color and $price array. Any idea what am I doing wrong?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

Are you getting the color and price variables from the URL? If so, you need to use $_GET not $_POST, and you may want to escape or validate your value.

Also I suggest not defining them as variables, because if there is no value for either of those taxonomies, you don't need the tax queries (it'll speed up the query).

Do it like this

$args = array( .....,
    'tax_query' => array( 'relation' => 'OR' ),
    ... );

if( $_GET['color'] )
    $args['tax_query'][] = array(
        'taxonomy' => 'color',
        'field' => 'term_id',
        'terms' => $color
    );
share|improve this answer
    
I am using a form and ajax, not url, so POST is ok. Btw. the color or price is there anyway, even if the array is empty. Btw. could you write your code a little more specific I don;t get what you are saying at all? –  Derfder Jul 31 '13 at 16:22
    
Thanks seems to be working nice. –  Derfder Jul 31 '13 at 17:20
    
I was going to say, that's pretty specific, not sure how to be more specific without doing your work for you. lol –  Eric Holmes Aug 1 '13 at 14:30
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.