我想显示自定义分类法的术语子级。目前,我可以使用get_term_children, 但是使用这个,它显示孩子和孙子,我想避免这个,并且只显示直系子。
这就是我现在拥有的(但它会输出孩子和孙子):
<?php
$term_id = get_queried_object_id();
$taxonomy_name = \'mytaxname\';
$termchildren = get_term_children( $term_id, $taxonomy_name );
foreach ( $termchildren as $child ) {
    $term = get_term_by( \'id\', $child, $taxonomy_name );
    echo \' <div class="product-archive">\';
        echo \'<div class="post-title">
      <h3 class="product-name"><a href="\' .get_term_link( $term, $taxonomy_name ). \'">\' .$term->name. \'</a></h3>  
    </div>
  </div>\';  }
?>
 这就是我努力工作的目的,所以它只显示直系子女:
<?php
$term_id = get_queried_object_id(); 
$taxonomy_name = \'mytaxname\';
$args = array(\'parent\' => $term_id,\'parent\' => $term_id );
$termchildren = get_terms( $taxonomy_name, $args);
foreach ( $termchildren as $child ) {
    $term = get_term_by( \'id\', $child, $taxonomy_name );
    echo \' <div class="product-archive">\';
        echo \'<div class="post-title">
      <h3 class="product-name"><a href="\' .get_term_link( $term, $taxonomy_name ). \'">\' .$term->name. \'</a></h3>  
    </div>
  </div>\';  }
?>
 这给了我一个错误:
Catchable fatal error: Object of class WP_Error could not be converted to string in...
我做错了什么?
谢谢
 
                    最合适的回答,由SO网友:Charles Clarkson 整理而成
                    使用get_terms() 改为函数:
$term_children = get_terms(
    \'mytaxname\',
    array(
        \'parent\' => get_queried_object_id(),
    )
);
if ( ! is_wp_error( $terms ) ) {
    foreach ( $term_children as $child ) {
        echo \'
            <div class="product-archive">
                <div class="post-title">
                    <h3 class="product-name"><a href="\' . get_term_link( $child ) . \'">\' . $child->name . \'</a></h3>
                </div>
            </div>
        \';
    }
}
get_terms() 可以返回WP\\u错误对象,因此您需要检查它是否返回。它返回一个术语对象数组,因此您不再需要使用
get_term_by(). 自从
$child 是一个术语对象,
get_term_link() 不需要第二个参数。
get_terms() 第二个参数有更多选项。你应该看看。