简体   繁体   English

如何从当前父类别中获取Woocommerce所有子类别

[英]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 - 只需在get_terms查询中添加您的父term_id,即可获取其所有子项,如下所示 -

$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: 您可以从产品类别术语Id中使用WordPress专用函数get_term_children()

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

It return a array of children terms Ids. 它返回一系列子项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' );
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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