简体   繁体   中英

How get Woocommerce all child category from current parent category

I want that I have some product categories on one page when I click on them, then I should get her child's categories. and I want that this work should be complete on the single page not more than pages How can i do this work

Simply add your parent term_id in your get_terms query to fetch all its children as follows -

$cat_args = array(
    'orderby'    => 'name',
    'order'      => 'ASC',
    'hide_empty' => false,
    'parent'     => $parent_term_id, // set your parent term id
);

$child_categories = get_terms( 'product_cat', $cat_args );

// since wordpress 4.5.0
$cat_args = array(
    'taxonomy'   => "product_cat",
    'orderby'    => 'name',
    'order'      => 'ASC',
    'hide_empty' => false,
    'parent'     => $parent_term_id, // set your parent term id
);
$child_categories = get_terms($cat_args);

It will returns all childs terms objects

You can use WordPress dedicated function get_term_children() from a product category term Id:

$child_terms_ids = get_term_children( $term_id, 'product_cat' );

It return a array of children terms Ids.


For product category archive pages, you can use:

// get the current product category term ID
if ( is_product_category() ) {
    $term_id = (int) get_queried_object_id();
}

if ( term_exists( $term_id, 'product_cat' ) ) {
    $child_terms_ids = get_term_children( $term_id, 'product_cat' );

    // Loop through child terms Ids
    foreach ( $child_terms_ids as $child_term_id ) {
        $child_term = get_term_by( 'term_id', $child_term_id, 'product_cat' );
        // The term name
        $child_name = $child_term->name;
        // The term link
        $child_link = get_term_link( $child_term, 'product_cat' );
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM