How to output children product categories on parent product category page?

Viewed 71

I am trying to get the children product categories to display on the parent product category page. The below code I have used works however it outputs all product categories not the children of the current product category I'm on.

Also I am struggling to get the category description to output a trimmed version of the text.

Any help would greatly be appreciated.

<?php
            
$product_categories = get_terms( 'product_cat', 'hide_empty=0' );
if ( ! empty( $product_categories ) && ! is_wp_error( $product_categories ) ) {
    foreach ( $product_categories as $category ) {
        
        $cat_page_link = esc_url( get_term_link( $category ) );
        
echo '<div class="blog-archive-single" onclick="location.href='. $cat_page_link .';">';
    echo '<a href="'. $cat_page_link .'">';
        echo '<div class="blog-archive-single-image">';
            if ( has_post_thumbnail() ) {
                echo '<p>';
                    the_post_thumbnail("full");
                echo '</p>';
            } else {
                echo'<p><img src="/wp-content/uploads/woocommerce-placeholder.png"/></p>';
            }
        echo '</div>';
        echo '<div class="blog-archive-single-content">';
            echo '<div class="single-tile-heading small-heading">';
                echo '<h3 class="title">';
                    echo esc_html( $category->name );
                echo '</h3>';
            echo '</div>';
            echo '<div class="blog-archive-content">';
                echo '<p>'. wp_trim_words( category_description($category_id), 20, '...' ) .'</p>';
            echo '</div>';
            echo '<div class="blog-archive-button">';
                echo '<div class="blog-archive-button-inner">';
                    echo '<span class="read-more-button">View Details</span>';
                    echo '<div class="blog-button-icon">';
                        echo '<i class="fa-solid fa-chevron-right"></i>';
                    echo '</div>';
                echo '</div>';
            echo '</div>';      
        echo '</div>';
    echo '</a>';
echo '</div>';      
    
    }
}
?>
1 Answers

Use get_term_children function to get child categories.

$main_term = get_queried_object();
$child_ids = get_term_children( $main_term->parent, 'product_cat' );
foreach ( $child_ids as $child_id ) {
    if( $child_id != $main_term->term_id ) {
        $term = get_term_by( 'id', $child_id, 'product_cat' );
        echo '<li><a href="' . get_term_link( $child_id, 'product_cat' ) . '">' . $term->name . '</a></li>';
    }
}

Check it out: https://wordpress.stackexchange.com/questions/361045/get-child-product-categories-from-parent-product-category-in-woocommerce#answer-361046

Related