简体   繁体   中英

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. I am able to get an array of product category IDs with the WordPress function, get_term_children .

$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. Here is what I am getting. The odd thing is that I can see the loop is grabbing all the IDs from $category_children .

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?

If you look at the documentation of get_category() , you can see that it uses the function get_term() , with the taxonomy 'category'.

Instead of using get_category to fetch your term children, use get_term() directly like :

$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.

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