最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - How to fix "Object of class WP_Term could not be converted to string"?

programmeradmin7浏览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;
        ?>

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
  • 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. – Jacob Peattie Commented Jul 11, 2020 at 4:55
Add a comment  | 

2 Answers 2

Reset to default 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;

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

}
发布评论

评论列表(0)

  1. 暂无评论