Wordpress 如何获得WooCommerce产品的直接父类别?
我有一个分级定制税(woocom产品),我正试图建立一些面包屑。我找到了Wordpress 如何获得WooCommerce产品的直接父类别?,wordpress,custom-taxonomy,Wordpress,Custom Taxonomy,我有一个分级定制税(woocom产品),我正试图建立一些面包屑。我找到了get_祖先(),我想用它来作为术语,但一旦我开始研究一个产品,我就迷路了。如何获得它所属的直接顶级类别(即产品列表) All Categories **term ID 192** -Sub Cat One **term id 204** -- Sub Cat Two (products listed out here) **term id 207** --- Product 这是我为解决这个问题而编写的代码,现在只需
get_祖先()
,我想用它来作为术语,但一旦我开始研究一个产品,我就迷路了。如何获得它所属的直接顶级类别(即产品列表)
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 ) );
}
}
您可以使用此代码构建面包屑。这将按层次顺序列出所有产品类别
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;
}
function cd\u get\u term\u parents($id,$taxonomy,$link=false,$separator='>>,$nicename=false,$visted=array()){
$chain='';
$parent=&get_term($id,$taxonomy);
如果(是错误($parent))
返回$parent;
如果($nicename){
$name=$parent->slug;
}否则{
$name=$parent->name;
}
如果($parent->parent&&($parent->parent!=$parent->term_id)&&!在_数组中($parent->parent,$visitored)){
$visited[]=$parent->parent;
$chain.=cd_get_term_parents($parent->parent,$taxonomy,$link,$separator,$nicename,$visted);
}
如果($link){
$chain.=''.$separator;
}否则{
$chain.=$name.$separator;
}
返回$chain;
}