使用CSS输出Woocommerce产品属性以归档页面和样式
问题描述:
在WooCommerce中,我尝试将产品属性输出到归档页面。我已经使用下面的代码成功输出了它们,但我无法单独设计它们的样式。使用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>
包装一个单独的类的名称,如“pa_pg
”,“pa_vg
”,“pa_nc
”。
例如我得到3 <div>
与相同的类名称。
对此有任何帮助吗?
答
简单地改变
echo '<div class="new-product-meta">';
到
echo '<div class="new-product-meta '.$attribute.'">';
给了我,我需要的结果。我应该指定我使用woocommerce 2.6.4。另外,有人编辑了原始问题的一部分,所以没有意义。
+0
此外,刚刚测试了我的代码,它完美适用于WooCommerce版本2.6+ – LoicTheAztec
答
首先,在WooCommerce中3+ WC_Product属性不能直接访问。所以我已经让你的代码兼容。
这是非常容易的属性分类蛞蝓添加到每个班级:
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文件或也以任何插件文件。
测试和工程
你有上课吗?为什么不使用'$ attribute'变量作为类名呢? – ferdynator