0

I am trying to use a tax query in my pre_get_posts function. All is working but not when the array has multiple IDs. Let's say my URL looks like: ?listing_cat[]=1&listing_cat[]=2

Now I am trying to filter out posts that are in those 2 categories. But my filter only gets the posts from the first category ID. I guess I will need a foreach function, but I am not sure how to implement this. Currently I have the code below. Now I know I can use filter by multiple terms with a comma, like : 'terms' => array($rt_cat_id[0], $rt_cat_id[1]), but I just need it to automatically get all the terms from the array $rt_cat_id and use those to filter the posts. How to accomplish that? Thanks

add_action( 'pre_get_posts', 'rt_tax_archive' );
function rt_tax_archive($query) {
$rt_cat_id = $_GET['listing_cat'];

if( isset( $rt_cat_id ) && ! empty( $rt_cat_id[0] ) ) {
            $tax_query[] = array(
                'taxonomy'  => 'listing_category',
                'field'     => 'id',
                'terms'     => array($rt_cat_id[0]),
           );
        }       


}

2 Answers 2

1

Just use:

'terms' => $rt_cat_id

I'll work for both array and single-based values.

Or you can simplify your code as follows:

if( isset( $_GET[ 'listing_cat' ] ) ) {
   $tax_query[] = array(
      'taxonomy' => 'listing_category',
      'field' => 'id',
      'terms' => $_GET[ 'listing_cat' ]
   );
}
0
0

So, the working code can be found below:

add_action( 'pre_get_posts', 'rt_tax_archive' );
function rt_tax_archive($query) {
$rt_cat_id = $_GET['listing_cat'];

if( isset( $rt_cat_id ) && ! empty( $rt_cat_id[0] ) ) {
            $tax_query[] = array(
            'relation' => 'OR',
            array(
            'taxonomy' => 'listing_category',
            'field' => 'id',
            'terms' => $rt_cat_id,
            ),
        );
        }       


}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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