如何修复“WP_Term 类的对象无法转换为字符串”?

09e*_*c09 2 php wordpress

我想遍历我拥有的每篇文章并获取分类/类别 ID。之后,我想将这些 id 输出到单个字符串中(不是数字值),并用空格分隔。

当我尝试回显字符串时出现此错误:“WP_Term 类的对象无法转换为字符串”

这是我到目前为止所拥有的:

<?php
          $taxonomy = wp_get_object_terms($post->ID, 'categories');
          $ids = "";
           
          foreach ($taxonomy as $cat) {
              $ids .= $cat;
          }
  ?>
Run Code Online (Sandbox Code Playgroud)

Flu*_*ten 5

正如错误消息所示,wp_get_object_terms返回一个对象数组WP_Term。如果您想从术语对象中获取 id,可以使用$term_object->term_id

在您的代码中,您应该使用$cat->term_id(并且您还将它们全部添加到字符串中,没有任何空格,所以我也添加了一个空格):

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

参考: