I know that i can use get_term_children() function to get childs for some parent for some taxonomy. For example, the taxonomy can be a product category.
For example, to display children product categories for a parent product category with ID = 70 i can use:
$taxonomyName = "product_cat";
$termID = "70";
$termchildren = get_term_children( $termID, $taxonomyName );
var_dump($termchildren);
echo '<ul>';
foreach ($termchildren as $child) {
$term = get_term_by( 'id', $child, $taxonomyName );
echo '<li><a href="' . get_term_link( $term->term_id, $term->taxonomy ) . '">' . $term->name . '</a></li>';
}
echo '</ul>';
I tried, the code is working. But what is the id of "THE VERY-VERY TOP / BASE / 0-level" product category in wp? I want to show only first-level it's parents. I tried "0" and "-1" as $termID, but no luck - it shows nothing. What is the right value?
CodePudding user response:
Try this:
<?php
$args = array(
'taxonomy' => 'product_cat',
'orderby' => 'name',
'show_count' => false, // true or false
'pad_counts' => false, // true or false
'hierarchical' => false, // true or false
'title_li' => '',
'hide_empty' => true // true or false
);
$product_categories = get_categories( $args );
echo '<ul>';
foreach ($product_categories as $category) {
if($category->category_parent == 0) { //this checks for 1st level that you wanted
echo '<a href="'. get_term_link($category->term_id, 'product_cat') .'">'. $category->name .'</a>';
}
}
echo '</ul>';
?>
References: