2017-04-25 120 views
0

我有一個分層定製稅(woocom產品),我正在嘗試構建一些麪包屑。我發現get_ancestors(),並且正在考慮使用這些術語,但是一旦我開始思考產品,我會迷失方向。如何獲得它所屬的最接近的頂級類別(即產品列表)?如何獲得WooCommerce產品的直接父類別?

All Categories **term ID 192** 
-Sub Cat One **term id 204** 
-- Sub Cat Two (products listed out here) **term id 207** 
--- Product 

這裏是我放在一起試圖弄清楚這一點的代碼,只需將註銷結果現在,

function build_breadcrumbs($product_cat_id, $type) { 

    if('product' === $type) { 
     $terms = get_the_terms($product_cat_id, 'product_cat'); 
     error_log(print_r( $terms, true)); 
    } 
    else { 
     $ancestors = get_ancestors($product_cat_id, $type); 
     error_log(print_r( $ancestors, true)); 
    } 

} 

回答

0

您可以使用此代碼來構建一個麪包屑。這將按層次順序列出所有產品類別。

function cd_get_term_parents($id, $taxonomy, $link = false, $separator = ' >> ', $nicename = false, $visited = array()) { 
    $chain = ''; 
    $parent = &get_term($id, $taxonomy); 
    if (is_wp_error($parent)) 
      return $parent; 

    if ($nicename) { 
      $name = $parent->slug; 
    } else { 
      $name = $parent->name; 
    } 

    if ($parent->parent && ($parent->parent != $parent->term_id) && !in_array($parent->parent, $visited)) { 
      $visited[] = $parent->parent; 
      $chain .= cd_get_term_parents($parent->parent, $taxonomy, $link, $separator, $nicename, $visited); 
    } 

    if ($link) { 
      $chain .= '<a href="' . get_term_link($parent, $taxonomy) . '" title="' . esc_attr(sprintf(_e("View all posts in %s"), $parent->name)) . '">'.$parent->name.'</a>' . $separator; 
    } else { 
      $chain .= $name.$separator; 
    } 
    return $chain; 
} 
相關問題