简体   繁体   English

WordPress get_category在forloop中不起作用

[英]WordPress get_category not working in a forloop

I'm trying to display data from all of the child product categories based on a given parent product category in woocommerce. 我正在尝试根据woocommerce中给定的父产品类别显示所有子产品类别的数据。 I am able to get an array of product category IDs with the WordPress function, get_term_children . 我可以使用WordPress函数get_term_children获得一系列产品类别ID。

$category_children = get_term_children( 25, 'product_cat' );

foreach ( $category_children as $category_id ) {
    echo '<br> cat ID' . $category_id;

    echo '<pre>';
    print_r(get_category($category_id));
    echo '</pre>';
}

The issue is when I try to display that data in a loop. 问题是当我尝试循环显示该数据时。 In this case, I have two child product categories. 在这种情况下,我有两个子产品类别。 My loop will only return data for all but the last ID. 我的循环只会返回除最后一个ID之外的所有ID的数据。 Here is what I am getting. 这就是我得到的。 The odd thing is that I can see the loop is grabbing all the IDs from $category_children . 奇怪的是,我可以看到循环正在从$category_children获取所有ID。

cat ID 26
WP_Term Object
(
    [term_id] => 26
    [name] => Shirts
    [slug] => shirts
    [term_group] => 0
    [term_taxonomy_id] => 26
    [taxonomy] => product_cat
    [description] => 
    [parent] => 25
    [count] => 2
    [filter] => raw
    [meta_value] => 0
    [cat_ID] => 26
    [category_count] => 2
    [category_description] => 
    [cat_name] => Shirts
    [category_nicename] => shirts
    [category_parent] => 25
)
cat ID 27  

Where is the WP_Term Object for 27. Am I not using get_category correctly or do I need to unset it or something? 27的WP_Term对象在哪里?我没有正确使用get_category还是需要取消设置它?

If you look at the documentation of get_category() , you can see that it uses the function get_term() , with the taxonomy 'category'. 如果查看get_category()文档 ,您会发现它使用了功能get_term()和分类法“ category”。

Instead of using get_category to fetch your term children, use get_term() directly like : 与其使用get_category来获取您的学期孩子, get_term()直接使用get_term()

$category_children = get_term_children( 25, 'product_cat' );
    foreach ($category_children as $category_id) {
        echo '<br> cat ID' . $category_id;

        echo '<pre>';
        print_r(get_term($category_id, 'product_cat'));
        echo '</pre>';
    }
}

Also get_term($category_id) without the taxonomy 'product_cat' works. 同样, get_term($category_id)不能使用分类法“ product_cat”。

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

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