如何获得Woocommerce顶级产品类别?

时间:2019-05-02 11:25:09

标签: wordpress woocommerce hook-woocommerce

我正在尝试在主页模板中检索顶级产品类别。我使用了下面的代码,但不知道为什么它不起作用。

 <?php
          global $post, $product;
    $taxonomy = 'product_cat'; //Choose the taxonomy
    $terms = get_terms( $taxonomy ); //Get all the terms

    foreach ($terms as $term) { //Cycle through terms, one at a time

    // Check and see if the term is a top-level parent. If so, display it.
    $parent = $term->parent;
     if ( $parent=='0' ) {

      $term_id = $term->term_id; //Define the term ID
      $term_link = get_term_link( $term, $taxonomy ); //Get the link to the archive page for that term
      $term_name = $term->name;
      echo '<a class="ccats" href="' . $term_link . '"><span class="label">' . $term_name . '</span></a>';
    } }
    ?>

请帮助我获得顶级类别。

2 个答案:

答案 0 :(得分:2)

您可以这样使用:

<?php
    $taxonomy = 'product_cat';
    $orderby = 'title';
    $show_count = 0; // 1 for yes, 0 for no
    $pad_counts = 0; // 1 for yes, 0 for no
    $hierarchical = 1; // 1 for yes, 0 for no
    $title = '';
    $empty = 1;
    $order = 'ASC';

    $args = array(
        'taxonomy' => $taxonomy,
        'orderby' => $orderby,
        'show_count' => $show_count,
        'pad_counts' => $pad_counts,
        'hierarchical' => $hierarchical,
        'title_li' => $title,
        'hide_empty' => $empty,
        'order' => $order,
        'parent' => 0
    );

    $terms = get_categories( $args );

    foreach ($terms as $term) { //Cycle through terms, one at a time

    // Check and see if the term is a top-level parent. If so, display it.
        if($term->category_parent == 0){

          $term_id = $term->term_id; //Define the term ID
          $term_link = get_term_link( $term, $taxonomy ); //Get the link to the archive page for that term
          $term_name = $term->name;
          echo '<a class="ccats" href="' . $term_link . '"><span class="label">' . $term_name . '</span></a>';
        } 
    }
?>

答案 1 :(得分:2)

get_terms()函数中只需要以下参数:

$terms = get_terms( array('taxonomy' => 'product_cat', 'parent' => 0) );

foreach ( $terms as $term ){
    $term_link = get_term_link( $term, $taxonomy );

    echo '<a class="ccats" href="'.$term_link.'"><span class="label">'.$term->name.'</span></a>';
}

这里是all available arguments,可以在get_terms()函数中使用。


对于产品类别图片:Get and display the product category featured image in Woocommerce