I want to retrieve a list of term Ids based on the current category ID.
At the moment I’m using the following code:
$product_cat_items = get_queried_object();
$product_cat_id = $product_cat_items->term_id;
$product_cat_child = get_term($product_cat_id, 'product_cat');
$product_cat_parent = $product_cat_child->parent;
$product_cat_related= get_terms('product_cat', array( 'parent' => $product_cat_parent, 'exclude' => $product_cat_id ));
It’s working and I get an array of the terms.
But the probem is, that I only need the IDs from the term object to get a list like this:
123,345,678
Is there any way to extract such a list from the $product_cat_related
array?
This is the current output:
array(2) {
[0]=>
object(WP_Term)#26238 (10) {
["term_id"]=>
int(177)
["name"]=>
string(27) "Name"
["slug"]=>
string(21) "name"
["term_group"]=>
int(0)
["term_taxonomy_id"]=>
int(177)
["taxonomy"]=>
string(11) "product_cat"
["description"]=>
string(0) ""
["parent"]=>
int(140)
["count"]=>
int(8)
["filter"]=>
string(3) "raw"
}
[1]=> ....
}
2
Answers
I found a solution here: https://stackoverflow.com/a/25286095/1788961
For me this code works:
Since WordPress version 4.5.0, taxonomies should be passed via the "taxonomy" argument in the
$args
array (seeget_terms()
documentation).Also
get_queried_object()
already gives aWP_Term
Object when the queried Object is a taxonomy term.Also you can use
'fields' => 'ids'
as an argument inget_terms()
, to get only an array of term Ids instead of an array ofWP_term
Objects (seeWP_Term_Query
available arguments).To finish, you will use PHP
implode()
to get a string of coma separated terms Ids.So your code will be instead:
Tested and works.