5

I want to make a custom WP_Query using custom taxonomy terms ID´s.

Example of the term’s ID’s : 19,18,214,226,20

Why does this work:

$query_args = array (
    'post_type' => 'works’,
    'tax_query' => array(
        array(
            'taxonomy'  => 'materials',
            'field'     => 'term_id',
            'terms'     => array( 19,18,214,226,20 ),
        )
    ),
);

It shows all items from all taxonomy terms ID’s,

But this doesn’t:

$tax = '19,18,214,226,20';

$query_args = array (
    'post_type' => 'works',
    'tax_query' => array(
        array(
            'taxonomy'  => 'materials',
            'field'     => 'term_id',
            'terms'     => array( $tax ),
        )
    ),
);

Using the variable $tax the query result only shows items the first term ID (19), and ignores all the others.

Why does this happens and how can i use the variable in the tax_query instead of hardcode the ID’s ?

2 Answers 2

15

It looks like you are making an array with a single string inside.

Check if making $tax into an array before passing it will work:

$tax = array( 19, 18, 214, 226, 20 );

$query_args = array (
    'post_type' => 'works',
    'tax_query' => array(
        array(
            'taxonomy'  => 'materials',
            'field'     => 'term_id',
            'terms'     => $tax,
        )
    ),
);

If you need to make an array from a formatted string, you can use the explode PHP function that takes a delimiter and a string, and returns an array, like so:

$tax_string = '19,18,214,226,20';
$tax_array = explode( ',', $tax_string );

Hope that works!

0
0

Because in php, $tax = '19,18,214,226,20'; is a string. and you can't wrap a string within array() and create an array :)

You may need something like :

function comma_separated_to_array($string, $separator = ',')
{
  //Explode on comma
  $vals = explode($separator, $string);

  //Trim whitespace
  foreach($vals as $key => $val) {
    $vals[$key] = trim($val);
  }
  //Return empty array if no items found
  //http://php.net/manual/en/function.explode.php#114273
  return array_diff($vals, array(""));
}

and use it as

$terms= comma_separated_to_array($tax);
3
  • Great function for separating comma separated values into an array but overkill for the above question.
    – Tex0gen
    Jan 17, 2017 at 17:46
  • Thanks. 4 lines of code of less than 30 characters each it not an overkill, I think :)
    – codiiv
    Jan 17, 2017 at 18:10
  • 1
    Or just use $ids = explode(',', $tax); Jun 23, 2020 at 15:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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