如何在单循环中显示所有父类别的子类别?

时间:2017-11-22 作者:Lovin Nagi
$args = array(
    \'post_type\' => \'listing\',
    \'order\' => \'ASC\',
    \'hide_empty\' => false,
    \'parent\' => 0,
);

$listCatTerms = get_terms( \'listing-category\',$args);
    if ( ! empty( $listCatTerms ) && ! is_wp_error( $listCatTerms ) ){
        foreach ( $listCatTerms as $term ) {
            echo \'<li class="lp-wrap-cats" data-catid="\'.$term->term_id.\'">\'.$catIcon.\'<span class="lp-s-cat">\'.$term->name.\'</span></li>\';
            $defaultCats .=\'<li class="lp-wrap-cats" data-catid="\'.$term->term_id.\'">\'.$catIcon.\'<span class="lp-s-cat">\'.$term->name.\'</span></li>\';
        }
    }
3 个回复
SO网友:Sid

给你:

$args = array(
        \'post_type\' => \'listing\',
        \'order\' => \'ASC\',
        \'hide_empty\' => false,
        \'parent\' => 0,
    );

    $listCatTerms = get_terms( \'listing-category\',$args);
    if ( ! empty( $listCatTerms ) && ! is_wp_error( $listCatTerms ) ){ 
        echo "<ul>";   
        foreach ( $listCatTerms as $term ) {
            echo \'<li>\'.$term->name.\'</li>\';
            $child_terms = get_categories( array(
                \'parent\' => $term->term_id,
                \'hide_empty\' => 0 ));
            //var_dump($child_terms);
            echo "<ul>";
            foreach($child_terms as $child_term){
                echo \'<li> -- \'.$child_term->name.\'</li>\';
            }
            echo "</ul><br>";
        }
        echo "</ul>";   
    } 
这应该显示父类别及其所有子类别的名称。

SO网友:Sourav Kundu

您可以尝试此代码

$getterms=get_terms( \'products-category\', array( \'hide_empty\' => false, \'parent\' => 0 ));
foreach( $getterms as $parent_term ) 
{
  echo $parent_term->name;
  $getpchild=get_terms( \'products-category\', array( \'hide_empty\' => false, \'parent\' => $parent_term->term_id ) );
  foreach( $getpchild as $child_term ) 
  {
    echo $child_term->name;
  }

}

SO网友:Lovin Nagi
$args = array(
        \'post_type\' => \'listing\',
        \'order\' => \'ASC\',
        \'hide_empty\' => false,
        \'parent\' => 0,
    );

    $listCatTerms = get_terms( \'listing-category\',$args);

    if ( ! empty( $listCatTerms ) && ! is_wp_error( $listCatTerms ) ){ 
        echo "<ul>";   
            foreach($listCatTerms as $listCatTerm) {

                //parent categories
                echo \'<li>\'.$listCatTerm->name.\'</li>\';

                //get childern term ID  
                $term_children = get_term_children( $listCatTerm->term_id, \'listing-category\' );
                foreach (  $term_children as $child  ) {                                                
                    //Get all Term data from database by Term field and data.
                    $term = get_term_by( \'id\', $child, \'listing-category\' );
                    //childern categories of its parent category
                    echo \'<li class="lp-wrap-cats">\'.$term->name.\'</li>\';
                }
            }
        echo "</ul>"; 
    }
结束