How to display Sub category in wordpress custom theme

How to display Sub category in wordpress custom theme

 

get subcategory in loop on the basis of main (parent) category ( in archieve_product.php )

// Get the current category object
$current_category = get_queried_object();

// If we're on a category page and it's a product category

if ( is_product_category() && isset( $current_category->term_id ) ) {

// Get the parent category ID
$parent_category_id = $current_category->term_id;

// Get the subcategories (child categories) for the parent category

$args = array(
'taxonomy' => 'product_cat', // WooCommerce product categories
'parent' => $parent_category_id,
'hide_empty' => false, // Optionally hide empty categories
);

$subcategories = get_terms( $args );

// If there are subcategories, loop through them
if ( ! empty( $subcategories ) && ! is_wp_error( $subcategories ) ) {

?>

<div class="elementor-widget-container">
<ul class="products elementor-grid columns-3">

<?php

foreach ( $subcategories as $subcategory ) {

// Display each subcategory

$subcategory_link = get_term_link( $subcategory );
$term_id = get_queried_object()->term_id; // Get current category ID
$term_id = $subcategory->term_id;  // Get current sub category ID
$thumbnail_id = get_woocommerce_term_meta($term_id, 'thumbnail_id', true); // Get category thumbnail ID
$image_url = wp_get_attachment_url($thumbnail_id); // Get the image URL

?>

<!-- loop start -->

<li>


<a href="<?php echo $subcategory_link; ?>" style="padding:10px; border:1px solid #f4f4f4">
    <img width="300" height="400" src="<?php echo $image_url; ?>" class="" alt="" decoding="async" 
sizes="(max-width: 300px) 100vw, 300px">
    <h3 class="" style="font-family: "Poppins", Sans-serif;  font-size: 22px;  font-weight: 600;
  text-transform: capitalize;
    font-style: normal;
    text-decoration: none;
    line-height: 1.2em;
    letter-spacing: 0px;"><?php echo $subcategory->name; ?>
</h3>

</a>

</li>

<!-- loop end -->

<?php
}
?>

</ul>
</div>


<style>

.elementor-4666 .elementor-element.elementor-element-a04f4b2.elementor-wc-products ul.products{
   display:none;
} 

</style>

<?php
} else {

}

}
admin side

add_action( 'display_product_subcategories', 'product_subcategories', 1 );
function product_subcategories( $args = array() ) {

    $parentid = get_queried_object_id();
    $args = array(
        'parent' => $parentid
    );
    
    $terms = get_terms( 'product_cat', $args );
    
    if ( $terms ) {
        echo '<ul class="list-style v1">';
    
        foreach ( $terms as $term ) {
            echo '<li class="type">';                 
                    echo '<a href="' .  esc_url( get_term_link( $term ) ) . '" class="' . $term->slug . '">';
                        echo $term->name;
                    echo '</a>';
            echo '</li>';
        }
    
        echo '</ul>';
    }
}
<?php do_action( 'display_product_subcategories' ); ?>

 

 

 

 

Leave a Reply