Only display Woocommerce child product categories
13,137
Solution 1
You can add this to woocommerce/archive-product.php file
$queried_object = get_queried_object();
$parent = $queried_object->term_id;
$categories = get_term_children( $parent, 'product_cat' );
if ( $categories && ! is_wp_error( $category ) ) :
echo '<ul>';
foreach($categories as $category) :
$term = get_term( $category, 'product_cat' );
echo '<li>';
echo '<a href="'.get_term_link($term).'" >';
echo $term->name;
echo '</a>';
echo '</li>';
endforeach;
echo '</ul>';
endif;
This will only work on your archives. And categories with children.
It will also output grand child categories.
Hope this helps.
Solution 2
Here is a way to get only product subcategories linked list ordered by name ASC:
// The product category taxonomy
$taxonomy = 'product_cat';
// Get the parent categories IDs
$parent_cat_ids = get_terms( $taxonomy, array(
'parent' => 0,
'hide_empty' => false,
'fields' => 'ids'
) );
// Get only "child" WP_Term Product categories
$subcategories = get_terms( $taxonomy, array(
'exclude' => $parent_cat_ids,
'orderby' => 'name',
'order' => 'asc',
'hide_empty' => false,
) );
if( ! empty( $subcategories ) ){
echo '<ul>';
foreach ($subcategories as $subcategory) {
echo '<li>
<a href="'. get_term_link($subcategory) .'" >' . $subcategory->name.'</a>
</li>';
}
echo '</ul>';
}
The code is tested and works
Related videos on Youtube
Author by
CharlyAnderson
Updated on June 04, 2022Comments
-
CharlyAnderson almost 2 years
I am currently using the following code to fetch WooCommerce product categories:
<?php $orderby = 'name'; $order = 'asc'; $hide_empty = false ; $cat_args = array( 'orderby' => $orderby, 'order' => $order, 'hide_empty' => $hide_empty, ); $product_categories = get_terms( 'product_cat', $cat_args ); if( !empty($product_categories) ){ echo '<ul>'; foreach ($product_categories as $key => $category) { echo '<li>'; echo '<a href="'.get_term_link($category).'" >'; echo $category->name; echo '</a>'; echo '<li>'; } echo '</ul>'; } ?>
This currently displays all categories, however I wish this to only show the child categories.
For example, if you are on the Category 1 page, it should show all children within that category only.
I've looked at many examples on here but have been unable to find something that works for what I need.
-
Satish over 6 yearsCan you share some sample query result?
-
Admin over 6 yearsYou don't send your current category as a parameter, also your SQL query must filter results with this parameter. If you can share your SQL query we can observe it.
-