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

I basically want to loop through each post I have and get the taxonomycategory id. After that I want to output those id

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

}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742273162a4413083.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信