列出所有 WooCommerce 产品属性名称

List all WooCommerce product attribute names

Woocommerce 是否有在主要 Woocomerce 模板之外列出属性名称的简短方法,即:single-product 或 product-archive?

这段代码几乎给了我想要的结果,它将输出我的 4 个属性标题,但重复每个产品的属性名称。我所需要的只是输出我的属性名称列表。

$query_args = array(
        'status'    => 'publish',
        'limit'     => -1,
    );
    foreach( wc_get_products($query_args) as $product ){
        foreach( $product->get_attributes() as $taxonomy => $attribute ){
            $attribute_name = get_taxonomy( $taxonomy )->labels->singular_name;
            foreach ( $attribute->get_terms() as $term ){
               echo '<li class="pa-filter-item"><a href="">' . $attribute_name . '</a></li>';
            }
        }
    }

目的是输出将用于创建过滤器的属性名称列表,以允许在自定义模板页面而不是 Woocommerce 页面中过滤术语。

如果您不使用可在单个产品上设置的自定义属性,则可以使用 wc_get_attribute_taxonomies() 函数获取所有产品属性分类对象,例如:

foreach ( wc_get_attribute_taxonomies() as $attribute ) {
    echo '<li class="pa-filter-item"><a href="">' . $attribute->attribute_label . '</a></li>';
}

或者您可以使用自定义 WPDB 查询:

global $wpdb;

$attribute_labels = $wpdb->get_col( "SELECT attribute_label FROM {$wpdb->prefix}woocommerce_attribute_taxonomies WHERE attribute_name != '' ORDER BY attribute_name ASC;" );

foreach ( $attribute_labels as $attribute_label ) {
    echo '<li class="pa-filter-item"><a href="">' . $attribute_label . '</a></li>';
}