这是我的代码,我需要显示每个数组的名称:
黑
蓝色
绿色
foreach( $product->get_variation_attributes() as $taxonomy => $terms_slug ){
// To get the taxonomy object
$taxonomy_obj = get_taxonomy( $taxonomy );
$taxonomy_name = $taxonomy_obj->name; // Name (we already got it)
$taxonomy_label = $taxonomy_obj->label; // Label
// Setting some data in an array
$variations_attributes_and_values[$taxonomy] = array('label' => $taxonomy_obj->label);
foreach($terms_slug as $term){
// Getting the term object from the slug
$term_obj = get_term_by('slug', $term, $taxonomy);
$term_id = $term_obj->term_id; // The ID <== <== <== <== <== <== HERE
$term_name = $term_obj->name; // The Name
$term_slug = $term_obj->slug; // The Slug
$term_name = $term_obj->description; // The Description
// Setting the terms ID and values in the array
$variations_attributes_and_values[$taxonomy]['terms'][$term_obj->term_id] = array(
'name' => $term_obj->name,
'slug' => $term_obj->slug
);
}}
这是我的阵列:
Array(
[pa_color] => Array(
[label] => Color
[terms] => Array(
[8] => Array(
[name] => Black
[slug] => black'
)
[9] => Array(
[name] => Blue
[slug] => blue
)
[11] => Array(
[name] => Green
[slug] => green
)
)
))
我该怎么做?
/////新编辑
echo '<pre>'; print_r($term_obj->name);echo '</pre>';
我使用此代码显示名称,但只显示姓氏!
答案 0 :(得分:1)
这是我的aswer代码之一:Get the product variations attributes values term ID and name
在Woocommerce 3发布之前就完成了。
由于woocommerce 3+事情发生了一些变化。您不需要函数中的所有代码。所以这是一个安排好的版本,以满足您的需求。
请记住您可以为变量产品提供许多属性,因此您需要使用
foreach
循环为每个产品属性输出分隔值...
以下是代码:
foreach( $product->get_variation_attributes() as $taxonomy => $terms_slug ){
// To get the attribute label (in WooCommerce 3+)
$taxonomy_label = wc_attribute_label( $taxonomy, $product );
foreach($terms_slug as $term){
// Getting the term object from the slug
$term_name = get_term_by('slug', $term, $taxonomy)->name;
// Setting the terms ID and values in the array
$attributes_and_terms_names[$taxonomy_label][$term] = $term_name;
}
}
echo '<pre>'; print_r($attributes_and_terms_names); echo '</pre>';
然后你会得到:
Array
(
[Color] => Array
(
[0] => Black
[1] => Green
[2] => Red
)
)
用法示例输出:
foreach ( $attributes_and_terms_names as $attribute_name => $terms_name ){
// get the related attribute term names in a coma separated string
$terms_string = implode( ', ', $terms_name );
echo '<p>' . $attribute_name . ': ' . $terms_string . '</p>';
}
你会得到:
颜色:黑色,绿色,红色