我想获取产品附带的所有属性列表,
因此,如果属性存在,但不附加任何产品,则不会显示。
我可以像这样将所有属性显示为下拉列表:
$attributes = wc_get_attribute_taxonomies();
if($attributes) {
echo '<select name="all-attributes" id="all-attributes">';
foreach ( $attributes as $attribute ) {
echo '<option value="' . $attribute->attribute_name . '">' . $attribute->attribute_label . '</option>';
}
echo '</select>';
}
但是通过这种方式,即使没有附加属性,我也可以获取所有属性。
您能帮我吗?
要获得附加到产品的产品属性,请使用WC_Product
方法get_attributes()
,如:
// Get the defined WC_Product object (if needed)
global $product;
// If the WC_Product object is not defined (if needed)
if ( ! is_a( $product, 'WC_Product' ) ) {
// Get the WC_Product object from the post ID (if needed)
$product = wc_get_product( get_the_id() );
}
$data = array(); // Initializing variable
// Get Product attributes
if ( $attributes = $product->get_attributes() ) {
//Loop through product attibute taxonomies set for this product
foreach( $attributes as $taxonomy => $attribute ){
// Loop through each product attribute terms
foreach( $attribute->get_terms() as $term ){
// Set the data in an array
$data[$taxonomy][$term->term_id] = $term->name;
}
}
}
// Raw output (testing)
echo '<pre>' . print_r( $data, true ) . '</pre>';