duanben1324 2017-06-21 08:36
浏览 50
已采纳

WordPress获取类别不在for循环中工作

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?

展开全部

  • 写回答

1条回答 默认 最新

  • duanliao6789 2017-06-21 09:19
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?