0

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;
        ?>
1
  • Note that the taxonomy term is category, not category. If you use a taxonomy name that doesn't exist $taxonomy will be a WP_Error object, not an array. Jul 11 '20 at 4:55
2

According 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;
0

$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>';

}
1
  • Thanks for the help, I still get nothing when I echo $ids
    – 09eric09
    Jul 10 '20 at 22:54

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.