我有一个可以归为多个类别的产品,示例请看以下字符串:
在woocommerce中,如果我有productid,则可以执行以下操作:
function alg_product_categories_names2( $atts ) {
$product_cats = get_the_terms( $this->get_product_or_variation_parent_id( $this->the_product ), 'product_cat' );
$cats = array();
$termstest= '';
if ( ! empty( $product_cats ) && is_array( $product_cats ) ) {
foreach ( $product_cats as $product_cat ) {
if ( $term->parent == 0 ) { //if it's a parent category
$termstest .= ' PARENTCAT= '. $product_cat->name;
}
}
}
return htmlentities('<categories_names>'. $termstest .'</categories_names>');
}
但这只是返回产品ID的所有父类别。
cat1,cat2,subcat1,Cat3,subcat2
我很难过。给我所需的产品ID,在上面建立列表-应该返回的是:
“ Cat1> Product1” | “ Cat2> subcat1> Product1” | “ Cat3> subcat1> subcat2> Product1”
我基本上需要从产品ID重建每个类别路径。
答案 0 :(得分:0)
要获取某个产品类别的所有祖先,可以使用Wordpress
get_ancestors()
函数
以下自定义简码功能将为给定产品的每个产品类别输出,其祖先将产品类别存储在您的问题中定义的字符串中:
add_shortcode( 'product_cat_list', 'list_product_categories' )
function list_product_categories( $atts ){
$atts = shortcode_atts( array(
'id' => get_the_id(),
), $atts, 'product_cat_list' );
$output = []; // Initialising
$taxonomy = 'product_cat'; // Taxonomy for product category
// Get the product categories terms ids in the product:
$terms_ids = wp_get_post_terms( $atts['id'], $taxonomy, array('fields' => 'ids') );
// Loop though terms ids (product categories)
foreach( $terms_ids as $term_id ) {
$term_names = []; // Initialising category array
// Loop through product category ancestors
foreach( get_ancestors( $term_id, $taxonomy ) as $ancestor_id ){
// Add the ancestors term names to the category array
$term_names[] = get_term( $ancestor_id, $taxonomy )->name;
}
// Add the product category term name to the category array
$term_names[] = get_term( $term_id, $taxonomy )->name;
// Add the formatted ancestors with the product category to main array
$output[] = implode(' > ', $term_names);
}
// Output the formatted product categories with their ancestors
return '"' . implode('" | "', $output) . '"';
}
代码进入您的活动子主题(活动主题)的function.php文件中。经过测试,可以正常工作。
用法:
1)在产品页面的php代码中:
echo do_shortcode( "[product_cat_list]" );
2)在具有给定产品ID (例如,产品ID为 37
)的php代码中:
echo do_shortcode( "[product_cat_list id='37']" );
我认为输出中不需要产品名称,因为它是重复的(在每个产品类别上)。这样您将得到如下内容:
"Cat1" | "Cat2>subcat1" | "Cat3>subcat1>subcat2"