显示当前帖子(Wordpress)术语的层次结构



我正在尝试在Wordpress中显示当前帖子的术语层次结构,如下所示:

    $terms = get_the_terms( get_the_ID(), 'type' );
    if($terms) {
        foreach( $terms as $term ) {
            $term_parent = get_term_by("id", $term->parent, "type");
            $parent_term_link = get_term_link( $term_parent );
            if ($term->parent > 0) {
                echo '<a href="'. $parent_term_link .'">'. $term_parent->name . '</a> ';
            }
            // for the children now
            $children_terms = get_the_terms(get_the_ID(), 'type');
            if($children_terms) {
                foreach ( $children_terms as $children_term ) {
                    echo '<pre>';
                    var_dump($children_term);
                    echo '</pre>';
                    if ( $children_term->parent === $term_parent->term_id ) {
                        echo $term->name;
                        break;
                    }
                }
            }
        }
    }

我很讨厌它,但我得到了这个错误作为回报:

Notice: Trying to get property of non-object in /web/wp-content/themes/make-child/partials/entry-meta-post-footer.php on line 25
Notice: Trying to get property of non-object in /web/wp-content/themes/make-child/partials/entry-meta-post-footer.php on line 25

对于第 25 行:

if ( $children_term->parent === $term_parent->term_id ) {

如何避免此错误消息(即使它返回了良好的结果)?

以下是var_dump返回的内容:

object(WP_Term)#3205 (11) {
  ["term_id"]=>
  int(39)
  ["name"]=>
  string(3) "#10"
  ["slug"]=>
  string(2) "10"
  ["term_group"]=>
  int(0)
  ["term_taxonomy_id"]=>
  int(39)
  ["taxonomy"]=>
  string(4) "type"
  ["description"]=>
  string(0) ""
  ["parent"]=>
  int(25)
  ["count"]=>
  int(2)
  ["filter"]=>
  string(3) "raw"
  ["object_id"]=>
  int(44)
}
(good result between)
object(WP_Term)#3205 (11) {
  ["term_id"]=>
  int(39)
  ["name"]=>
  string(3) "#10"
  ["slug"]=>
  string(2) "10"
  ["term_group"]=>
  int(0)
  ["term_taxonomy_id"]=>
  int(39)
  ["taxonomy"]=>
  string(4) "type"
  ["description"]=>
  string(0) ""
  ["parent"]=>
  int(25)
  ["count"]=>
  int(2)
  ["filter"]=>
  string(3) "raw"
  ["object_id"]=>
  int(44)
}

谢谢

好的,

我在这里找到了我正在寻找的内容:https://wordpress.org/support/topic/display-hierarchical-taxonomy-list#post-3881067

<?php
$taxonomy = 'category'; // change this to your taxonomy
$terms = wp_get_post_terms( $post->ID, $taxonomy, array( "fields" => "ids" ) );
if( $terms ) {
  echo '<ul>';
  $terms = trim( implode( ',', (array) $terms ), ' ,' );
  wp_list_categories( 'title_li=&taxonomy=' . $taxonomy . '&include=' . $terms );
  echo '</ul>';
}
?>

最新更新