使用 CSS 输出 Woocommerce 产品属性以存档页面和样式

Output Woocommerce Product Attributes to Archive Pages and Style with CSS

在 WooCommerce 中,我试图将产品属性输出到存档页面。我已经使用下面的代码成功输出了它们,但无法单独设置它们的样式。

add_action( 'woocommerce_after_shop_loop_item_title', 'custom_display_post_meta', 9 );
function custom_display_post_meta() {
    global $product;
    $attr = array('pa_pg', 'pa_vg', 'pa_nc');
    foreach ( $attr as $attribute ) {
        $values = wc_get_product_terms( $product->id, $attribute, array( 'fields' => 'names' ) );
        echo '<div class="new-product-meta">';
        echo apply_filters( 'woocommerce_attribute', wpautop( wptexturize( implode( ', ', $values ) ) ), $attribute, $values );
        echo '</div>';
    }
}

我需要在 <div> 中用单独的 class 名称围绕每个名称,例如“pa_pg”、“pa_vg”、“[=15” =]'.

例如,我得到 3 个 <div> 具有相同的 class 个名字。

请问有什么帮助吗?

首先,在 WooCommerce 3+ WC_Product 中无法直接访问属性。所以我让你的代码兼容。

将属性分类 slug 添加到每个 class:

非常容易
add_action( 'woocommerce_after_shop_loop_item_title', 'custom_display_post_meta', 9 );
function custom_display_post_meta() {
    global $product;

    // Get the Product ID - WC 3+ compatibility
    $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;

    $product_attributes = array('pa_pg', 'pa_vg', 'pa_nc');

    foreach ( $product_attributes as $taxonomy ) {
        $values = wc_get_product_terms( $product_id, $taxonomy, array( 'fields' => 'names' ) );

        // => HERE we add the taxonomy name to the <div> class
        echo '<div class="new-product-meta '.$taxonomy.'">';
        echo apply_filters( 'woocommerce_attribute', wpautop( wptexturize( implode( ', ', $values ) ) ), $taxonomy, $values );
        echo '</div>';
    }
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

已测试并有效

简单地改变

echo '<div class="new-product-meta">';

echo '<div class="new-product-meta '.$attribute.'">';

给了我我需要的结果。我应该指定我使用的是 woocommerce 2.6.4。另外,有人编辑了部分原始问题,所以它没有意义。