09eric09
09eric09

Reputation: 187

How to fix “Object of class WP_Term could not be converted to string”?

I want to loop through each post I have and get the taxonomy/category id. After that I want to output those ids 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;
          }
  ?>

Upvotes: 2

Views: 7698

Answers (1)

FluffyKitten
FluffyKitten

Reputation: 14312

As the error message suggests, wp_get_object_terms returns an array of WP_Term objects. If you want to get the id from the term object, you can use $term_object->term_id.

In your code, you should be using $cat->term_id (and you are also adding them all to the string without any spaces so I've added a space in too):

$taxonomy = wp_get_object_terms($post->ID, 'categories');
$ids = "";
       
foreach ($taxonomy as $cat) {
    $ids .= " ".$cat->term_id;  // het the id from the term object
}

Reference:

Upvotes: 6

Related Questions