Use $query->set multiple times with pre_get_posts?

Think of this pseudo code

if sky == blue
  set a = 5
if grass == green
  set a = 7

What value will a have? Not 12.

This is the exact same situation. You are setting a specific parameter to a specific value. In the second call, you are overwriting your previous value. To avoid this, you can build the value (here the array) beforehand, and call ->set() only once.

$tax_query = array();
if( isset( $rt_term_id ) && ! empty( $rt_term_id ) ) {
    $tax_query[] = array(
        'taxonomy'  => 'vakantiesoorten_listing',
        'field'     => 'id',
        'terms'     => array($rt_term_id[0]),
    );
}
if( empty($_GET['location_geo_data']) && isset( $rt_term_id_land ) && ! empty( $rt_term_id_land ) ) {
    $tax_query[] = array(
        'taxonomy'  => 'landen_listing',
        'field'     => 'id',
        'terms'     => array($rt_term_id_land[0]),
    );
}
$query->set( 'tax_query', $tax_query );

Leave a Comment