对于我正在开发的 WC 插件,我需要找到定义产品变体的属性。因此,假设我们有一个可变产品,它具有颜色、尺寸、材质等属性,但只有尺寸定义了变化;所以我想要一个算法(我怀疑是否有一个单一的 WC 方法)来获取 Size 属性(或其 ID/slug)。
任何帮助将非常感激。
您可以使用可变产品中的
get_variation_attributes()
方法,例如:
global $product;
$product = wc_get_product(15);
if ( ! is_a($product, 'WC_Product') ) {
$product = wc_get_product(get_the_ID);
}
if ($product->is_type('variable') ) {
$output_html = '<ul class="variations-attributes">';
foreach( $product->get_variation_attributes() as $attribute => $values ) {
$label_name = wc_attribute_label( $attribute, $product );
$term_names = $product->get_attribute($attribute);
$output_html .= sprintf('<li>%s: %s</li>', $label_name, $term_names);
}
// Test output
echo $output_html . '</ul>';
}
}