显示第二级产品类别

时间:2018-10-23 10:11:38

标签: wordpress woocommerce

似乎无法找出在下拉菜单中显示woocommerce产品类别第二级的方式。

到目前为止,我有这个

function lvl_1()
    {  
        $args = array(
            'show_option_all'    => ' ',
            'name'         => 'Marka',
            'taxonomy'     => 'product_cat',
            'orderby'      => 'name',
            'show_count'   => 0,
            'pad_counts'   => 0,
            'hierarchical' => 1,
            'hide_empty'   => 0,
            'parent'       => 0,
        );
        $lvl_1_categories = wp_dropdown_categories( $args );  

    }
    function lvl_2()
    {
        $args = array(
            'taxonomy'     => 'product_cat',           
            'parent'       => 0,
        );
        $lvl_1_categories = get_categories( $args );  
        $args2 = array(
            'show_option_all'    => ' ',
            'name'         => 'Modelis',
            'taxonomy'     => 'product_cat',
            'orderby'      => 'name',
            'show_count'   => 0,
            'pad_counts'   => 0,
            'hierarchical' => 1,
            'hide_empty'   => 0,  
            // Somewhere here i should get a value of first level elements to dispaly their childer, thats what i think.
            );
        $lvl_2_categories = wp_dropdown_categories( $args2 );  
    }

lvl_1函数可以正常工作,它可以显示顶级类别,但是有没有办法使用此wp_dropdown_categories()函数来显示第二级类别?

1 个答案:

答案 0 :(得分:0)

放置以下代码并获取所有类别的列表。

$categories = get_categories( array(
                'type'        => 'post',
                'child_of'    => 0,
                'orderby'     => 'id',
                'order'       => 'ASC',
                'hide_empty'  => 0,
                'hierarchical'=> 0,           
                'taxonomy'    => 'category',
                'parent' => 0                                              
            ) );

$top_level_ids = [];
foreach( $categories as $category ) {
    if( ! $category->parent ) {
        $top_level_ids[] = $category->term_id;
    }
}
//print_r($top_level_ids);die;
$categories = get_categories( array(
                'type'        => 'post',
                'child_of'    => 0,
                'orderby'     => 'id',
                'order'       => 'ASC',
                'hide_empty'  => 0,
                'hierarchical'=> 0,           
                'taxonomy'    => 'category',
            ) );

foreach( $categories as $category ) {
    // Only output if the parent_id is a TOP level id
    if( in_array( $category->parent, $top_level_ids )) {
        echo $category->term_id . ', ' . $category->slug . ', ' . $category->name . '<br />';
    }
} die;