WP Query with multiple categories – passing an array works?

According to the codex, to query posts that can belong to any of a collection of categories, we need to do something like this:

$query = new WP_Query( array( 'cat' => '2,6,17,38' ) );

https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters

However, I have the following, which works, and I’m not sure why.

  $args = array(
    'cat' => $related_cat_ids,
    'posts_per_page' => -1,
  );
  $query = new WP_Query($args);

The reason why I’m confused is because $related_cat_ids is actually an array, but the example clearly shows a string of numbers, seperated by commas, for the ‘cat’ value.

Is this something I should be concerned about? Will my code all of a sudden stop working in a future WordPress release? It’s more convenient for my case to keep using the array, rather than format it into that string. The reason being is that I’m using get_the_category() to get the categories dynamically, and then pushing the IDs from that array into my new array.

2 Answers
2

I understand your confusion but you haven’t something to worry about as behinds the scenes WordPress make all the necessary steps to make it work.

For example, take the following code from the class-wp-query.php

// If querystring 'cat' is an array, implode it.
if ( is_array( $q['cat'] ) ) {
    $q['cat'] = implode( ',', $q['cat'] );
}

Is checking to see if is an array and quickly transform the result to a comma-separated string.

Another way will be using the other options like:

 category__and           An array of category IDs (AND in).
 category__in            An array of category IDs (OR in, no children).
 category__not_in        An array of category IDs (NOT in).

More on this in Category_Parameters

But again I would hold to use the way you find more comfortable.

It perfectly fine to use the array() format if you find it more useful besides this is what make WordPress a fun and useful tool to work on.

Leave a Comment