首頁>Web>source

我正在使用這两个函式,从而获得了自定義分類法的頂級父類別.這些已经過測試,可以按預期工作。

但是,現在我正在尋找一種輸出子類別而不是父類別的方法。

function get_term_top_most_parent( $term, $taxonomy ) {
    // Start from the current term
    $parent  = get_term( $term, $taxonomy );
    // Climb up the hierarchy until we reach a term with parent = '0'
    while ( $parent->parent != '0' ) {
        $term_id = $parent->parent;
        $parent  = get_term( $term_id, $taxonomy);
    }
    return $parent;
}
function get_top_parents( $taxonomy ) {
    // get terms for current post
    $terms = wp_get_object_terms( get_the_ID(), $taxonomy );
    $top_parent_terms = array();
    foreach ( $terms as $term ) {
        //get top level parent
        $top_parent = get_term_top_most_parent( $term, $taxonomy );
        //check if you have it in your array to only add it once
        if ( !in_array( $top_parent, $top_parent_terms ) ) {
            $top_parent_terms[] = $top_parent;
        }
    }
    // build output (the HTML is up to you)
    foreach ( $top_parent_terms as $term ) {
          //Add every term
          $output = $term->slug;
    }
    return $output;
}
最新回復
  • 6月前
    1 #

    如果用於产品類別,則此功能仅需要類別ID即可知道其子類別:

    function cat_childs( $term_id = 0) {
      $children = get_terms( array(
            'child_of'      => $term_id,
            'taxonomy'      => 'product_cat',
            'hide_empty'    => true,
            'fields'        => 'ids',
      ));
    return ( $children );
    }
    

    可以這樣稱呼:

    cat_childs(1234);
    

    因為它可以返迴多个我们可以先檢查的

    $a = cat_childs(1234);
    echo '<pre>';
    print_r($a);
    

    如果是這樣,我们只需要做一个foreach迴圈就可以全部获取。

    這是我的代碼,以便在使用cat_childs()函式檢查是否需要下一个迴圈的第三代产品之前,使用它们全部製作選單。

    $cat_args = array( 'orderby' => 'name', 'order' => 'asc', 'hide_empty' => true);
    $cats = get_terms( 'product_cat', $cat_args );
    foreach ($cats as $key => $cat):
      if ($cat->parent == 0): ?>
        <p><a href="<?php echo get_term_link($cat) ?>"  style="color:red;"><?php echo $cat->name; ?></a></p><?php
        if (cat_childs($cat->term_id)):
          foreach ($cats as $key => $cat2):
            if ($cat2->parent == $cat->term_id): ?>
              <p><a href="<?php echo get_term_link($cat2) ?>" style="margin-left:20px;  color:blue;"><?php echo $cat2->name; ?></a></p><?php
              if (cat_childs($cat2->term_id)):
                foreach ($cats as $key => $cat3):
                  if ($cat3->parent == $cat2->term_id): ?>
                    <p><a href="<?php echo get_term_link($cat3) ?>" style="margin-left:40px; color:green;"><?php echo $cat3->name; ?></a></p><?php
                  endif;
                endforeach;
              endif;
            endif;
          endforeach;
        endif;
      endif;
    endforeach;
    

  • wordpress:如何將自定義HTML添加到存档頁面帖子的內容中?
  • wordpress:wordPress管理面板表中的本地發佈日期