Junky
Junky

Reputation: 1026

Conditional meta_query and tax_query for wp_query

Depending on some variable, I need to get all posts or a list of posts filtered by a custom field.

I can get all posts and I can get the list of posts filtered by the custom field and tag with separate queries but I'm trying to combine the queries.

The single query returns the filtered list:

$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array( 
    'post_type' => 'listings',
    'post_status' => 'publish',
    'orderby' => 'publish_date',
    'order' => 'ASC',                            
    'orderby' => 'date',
    'posts_per_page' => '4',
    'paged' => $paged,
    'meta_query' => array(
        array(
            'key' => 'listing_status',
            'value' => array('active','sold'),
            'compare' => 'IN'
        )
    ),
    'tax_query' => array(
        array(
            'taxonomy' => 'post_tag',
            'field'    => 'slug',
            'terms'    => $agentslug,
        ),
    )                        
);
$query = new WP_Query( $args );

but I also might need the list unfiltered. I tried combining the queries:

$meta_query = array();
$tax_query = array();

if ( $agentslug ) {
    $meta_query[] = array(array(
        'key' => 'listing_status',
        'value' => array('active','sold'),
        'compare' => 'IN'
    ));
    $tax_query[] = array(array(
        'taxonomy' => 'post_tag',
        'field'    => 'slug',
        'terms'    => $agentslug,
    ));
}

$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array( 
    'post_type' => 'listings',
    'post_status' => 'publish',
    'orderby' => 'publish_date',
    'order' => 'ASC',                            
    'orderby' => 'date',
    'posts_per_page' => '4',
    'paged' => $paged,
    'meta_query' => $meta_query,
    'tax_query' => $tax_query                  
);
$query = new WP_Query( $args );

but they both return the full list.

Upvotes: 0

Views: 2291

Answers (1)

jrswgtr
jrswgtr

Reputation: 2379

You are using 1 nested array to much

$meta_query = array();
$meta_query[] = array(array());

Acts the same as

$meta_query = array();
array_push( $meta_query, array(array()) )

And has the same result as

$meta_query = array(array(array()));

Change

if ( $agentslug ) {
    $meta_query[] = array(array(
        'key' => 'listing_status',
        'value' => array('active','sold'),
        'compare' => 'IN'
    ));
    $tax_query[] = array(array(
        'taxonomy' => 'post_tag',
        'field'    => 'slug',
        'terms'    => $agentslug,
    ));
}

To

if ( $agentslug ) {
    $meta_query[] = array(
        'key' => 'listing_status',
        'value' => array('active','sold'),
        'compare' => 'IN'
    );
    $tax_query[] = array(
        'taxonomy' => 'post_tag',
        'field'    => 'slug',
        'terms'    => $agentslug,
    );
}

Upvotes: 3

Related Questions