在WooCommerce子类别存档页面上显示子类别术语列表

时间:2020-08-05 12:07:29

标签: php wordpress woocommerce hierarchical taxonomy-terms

在Woocommerce中,我使用Get the subcategories of the current product category in Woocommerce archives回答功能,以在父类别页面上显示子类别列表

但是我只需要将其应用于特定的产品类别,并且不希望使用带有大量类别ID的数组。

我只需要在第一个子类别上显示列表,例如,我的主要父类别之一是“服装”,然后是子类别“衬衫”,然后是子子类别“无袖”。我只需要在第一个子类别(在本例中为“衬衫”)中显示它即可。

1 个答案:

答案 0 :(得分:1)

仅在主要类别存档页面上仅显示第一个子类别,请使用:

add_action('woocommerce_before_shop_loop', 'display_sub_subcategories', 10 );
function display_sub_subcategories() {
    $obj      = get_queried_object();
    $taxonomy = 'product_cat';

    if ( is_a($obj, 'WP_Term') && $taxonomy === $obj->taxonomy && 0 != $obj->parent ) {
        // Get sub-subcategories of the current subcategory
        $terms = get_terms([
            'taxonomy'    => $taxonomy,
            'hide_empty'  => true,
            'parent'      => $obj->term_id
        ]);

        if ( ! empty($terms) ) :

        $output = '<ul class="subcategories-list">';

        // Loop through product subcategories WP_Term Objects
        foreach ( $terms as $term ) {
            $term_link = get_term_link( $term, $taxonomy );

            $output .= '<li class="'. $term->slug .'"><a href="'. $term_link .'">'. $term->name .'</a></li>';
        }

        echo $output . '</ul>';
        endif;
    }
}