Search code examples
phpwordpresswoocommercehierarchical-datataxonomy-terms

List main product subcategories of a product category in WooCommerce


I have a category of WooCommerce products called "Product Types", and I'm trying to list all the categories underneath that, but NOT the child categories of those categories. For example, I have:

  • Product Types
    • Carbide Milles
    • Fishing Tools
      • Child Category

I want it to list "Carbide Mills" and "Fishing Tools", but NOT "Child Category".

Here's the code I have:

<ul>
<?php $terms = get_terms(
    array(
        'taxonomy'   => 'product_cat',
        'hide_empty' => false,
            'child_of' => 32,
            'post__not_in' => 25,
            'depth' => 1,
            'include_children' => false,
    )
);

// Check if any term exists
if ( ! empty( $terms ) && is_array( $terms ) ) {
    // Run a loop and print them all
    foreach ( $terms as $term ) { ?>
        <a href="<?php echo esc_url( get_term_link( $term ) ) ?>">
            <li data-mh="234908ju243">
            <?php echo $term->name; ?>
            </li>
        </a><?php
    }
} ?>
</ul>

But it's still returning the "Child Category". I'm not sure why limiting the depth to '1' and setting the 'include_children' to 'false' doesn't take care of the issue.


Solution

  • You should need to use the argument parent with your "Product Types" term Id, to get the direct child terms (subcategories) as follow:

    <ul>
    <?php 
    // Get the WP_Term object for "Product Types" product category (if needed)
    $parent_term = get_term_by('name', 'Product Types', 'product_cat' )->term_id;
    
    // Display "Product Types" category
    echo' <a href="' . esc_url( get_term_link( $parent_term ) ) . '">' . $parent_term->name . '</a><br>';
    
    // Get main direct subcategories
    $terms = get_terms( array(
        'taxonomy'   => 'product_cat',
        'hide_empty' => false,
        'parent'     => $parent_term->term_id,
    ) );
    
    // Check if any term exists
    if ( ! empty( $terms ) && is_array( $terms ) ) {
        // Loop through each term and print them all
        foreach ( $terms as $term ) {
            echo '<li data-mh="234908ju243">
            <a href="' . esc_url( get_term_link( $term ) ) . '">' . $term->name . '</a>
            </li>';
        }
    } ?>
    </ul>
    

    It should work.

    I have changed a bit your html structure as the <a> tag need to be inside the <li> tag.