如何将父子类别(woocommerce)获取到子类别模板

问题描述 投票:0回答:1

我尝试在子类别模板中显示父子类别。我使用下面的代码,它只是在父类别中显示子类别。

更新代码:

<?php
            $counter = 0;
            $term = get_queried_object();

            $children = get_terms( $term->taxonomy, array(
                'parent'    => $term->term_id,
                'hide_empty' => false
            ) );

            $categories = [ $term ];

            // If $children is an array just merge the "current" (parent) category with the children
            if ( is_array( $children ) ) {
                $categories = array_merge( $categories, $children );
            }


            foreach( $categories as $subcat ) {
                    echo '<ul><li><a href="' . esc_url(get_term_link($subcat, $subcat->taxonomy)) . '">' . $subcat->name . '</a></li></ul>';
            }
        ?>
wordpress woocommerce
1个回答
0
投票

在这种情况下,您正在查询所有“子项”,在尝试创建包含所有已有数据的数组时,只需构造它。

<?php
            $counter = 0;
            $term = get_queried_object();

            $children = get_terms( $term->taxonomy, array(
                'parent'    => $term->term_id,
                'hide_empty' => false
            ) );

            $categories = [ $term ];

            // If $children is an array just merge the "current" (parent) category with the children
            if ( is_array( $children ) ) {
                $categories = array_merge( $categories, $children );
            }


            foreach( $categories as $subcat ) {
                    echo '<ul><li><a href="' . esc_url(get_term_link($subcat, $subcat->taxonomy)) . '">' . $subcat->name . '</a></li></ul>';
            }
        ?>

您可以在上面的示例中看到,添加了一小段代码来将两个数组合并为一个数组。

© www.soinside.com 2019 - 2024. All rights reserved.