WooCommerce 版本 3+ 的更新
foreach( $product->get_variation_attributes() as $taxonomy => $terms_slug ){
// To get the attribute label (in WooCommerce 3+)
$taxonomy_label = wc_attribute_label( $taxonomy, $product );
// Setting some data in an array
$variations_attributes_and_values[$taxonomy] = array('label' => $taxonomy_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_description = $term_obj->description; // The Description
// Setting the terms ID and values in the array
$variations_attributes_and_values[$taxonomy]['terms'][$term_id] = array(
'name' => $term_name,
'slug' => $term_slug
);
}
}
低于 WooCommerce 版本 3
我在您的原始数据数组中没有看到任何重复的变体 ID…您的问题不是很清楚,因此很难猜测您正在查看的缺失 ID 是什么。然后我冒险回答,我认为丢失的 ID 是属性值中的术语 Id...
为了获取此术语 ID,我使用 Wordpress 功能get_term_by(), 这边走:
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_description = $term_obj->description; // The Description
// Setting the terms ID and values in the array
$variations_attributes_and_values[$taxonomy]['terms'][$term_id] = array(
'name' => $term_name,
'slug' => $term_slug
);
}
}
与:
echo '<pre>'; print_r($variations_attributes_and_values);echo '</pre>';
我会得到这个输出,每个属性的实际术语 ID对于产品变体(我已经安排了数组输出以使其更加紧凑):
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
)
)
)
[pa_bulk_quantity] => Array(
[label] => Bulk quantity
[terms] => Array(
[44] => Array(
[name] => Pack of 10 dozen
[slug] => pack-of-10-dozen
)
[45] => Array(
[name] => Case of 50 dozens
[slug] => case-of-50-dozens
)
)
)
)