I basically want to loop through each post I have and get the taxonomy/category id. After that I want to output those id's into a single string (not as a numeric value), separated by a space.
I get this error when I try to echo the string: "Object of class WP_Term could not be converted to string"
Here is what i have so far:
<?php
$taxonomy = wp_get_object_terms($post->ID, 'categories');
$ids = "";
foreach ($taxonomy as $cat) {
$ids .= $cat;
?>
I basically want to loop through each post I have and get the taxonomy/category id. After that I want to output those id's into a single string (not as a numeric value), separated by a space.
I get this error when I try to echo the string: "Object of class WP_Term could not be converted to string"
Here is what i have so far:
<?php
$taxonomy = wp_get_object_terms($post->ID, 'categories');
$ids = "";
foreach ($taxonomy as $cat) {
$ids .= $cat;
?>
Share
Improve this question
asked Jul 10, 2020 at 22:06
09eric0909eric09
52 bronze badges
1
|
2 Answers
Reset to default 2According to the docs for the Term object the ID is in the property term_id
So you need:
$ids = array();
foreach ($taxonomy as $tax) {
$ids[] = $tax->term_id;
}
$joinedIds = implode(" ", $ids);
// do something with $joinedIds;
$cat
is an object, not a string. You are also missing a closing bracket.
Try: $ids .= $cat->id . ' ';
It is often helpful to take a look at the returned structure and data:
foreach ($taxonomy as $cat) {
echo '<pre>'; var_dump( $cat ); echo '</pre>';
}
category
, notcategory
. If you use a taxonomy name that doesn't exist$taxonomy
will be aWP_Error
object, not an array. – Jacob Peattie Commented Jul 11, 2020 at 4:55