如何获得WooCommerce产品的直接父类别?

时间:2017-04-25 23:24:56

标签: wordpress custom-taxonomy

我有分级自定义税(woocom产品),我正在尝试构建一些面包屑。我发现get_ancestors()并且正在考虑将其用于条款,但是一旦我开始使用产品,我就会迷失方向。如何获得它所属的直接顶级类别(即产品列表)?

All Categories  **term ID 192**
-Sub Cat One  **term id 204**
-- Sub Cat Two (products listed out here) **term id 207**
--- Product

以下是我试图解决这个问题的代码,现在只记录结果,

function build_breadcrumbs( $product_cat_id, $type ) {

    if( 'product' === $type ) {
        $terms = get_the_terms($product_cat_id, 'product_cat');
        error_log( print_r(  $terms, true ) );
    }
    else {
        $ancestors = get_ancestors($product_cat_id, $type);
        error_log( print_r(  $ancestors, true ) );
    }

}

1 个答案:

答案 0 :(得分:0)

您可以使用此代码构建面包屑。这将按层次顺序列出所有产品类别。

function cd_get_term_parents( $id, $taxonomy, $link = false, $separator = ' >> ', $nicename = false, $visited = array() ) {
    $chain = '';
    $parent = &get_term( $id, $taxonomy );
    if ( is_wp_error( $parent ) )
            return $parent;

    if ( $nicename ) {
            $name = $parent->slug;
    } else {
            $name = $parent->name;
    }

    if ( $parent->parent && ( $parent->parent != $parent->term_id ) && !in_array( $parent->parent, $visited ) ) {
            $visited[] = $parent->parent;
            $chain .= cd_get_term_parents( $parent->parent, $taxonomy, $link, $separator, $nicename, $visited );
    }

    if ( $link ) {
            $chain .= '<a href="' . get_term_link( $parent, $taxonomy ) . '" title="' . esc_attr( sprintf( _e( "View all posts in %s" ), $parent->name ) ) . '">'.$parent->name.'</a>' . $separator;
    } else {
            $chain .= $name.$separator;
    }
    return $chain;
}