问题描述
我正在 WP + WooCommerce 中建立一家商店。我有不同类型的产品类别,如光盘和袋子。对于光盘产品,我有一些特定的属性,例如 Speed、Glide、Turn 和 Fade,这些属性没有任何其他产品类别。我想只在商店页面的产品图片下显示这些产品属性值。
我找到了一个代码,我为自己添加了一个分隔符号“|”,但这个分隔符号现在显示在所有可变产品下。
是否可以不将代码更改为变量,而仅针对特定的产品类别和子类别?
代码:
add_action( 'woocommerce_before_shop_loop_item_title','display_size_attribute',5 );
function display_size_attribute() {
global $product;
if ( $product->is_type('variable') ) {
$taxonomy = 'pa_speed';
echo '<span class="attribute-speed">' . $product->get_attribute($taxonomy) . '</span>' ;
echo ' | ';
$taxonomy = 'pa_Glide';
echo '<span class="attribute-Glide">' . $product->get_attribute($taxonomy) . '</span>';
echo ' | ';
$taxonomy = 'pa_Turn';
echo '<span class="attribute-Turn">' . $product->get_attribute($taxonomy) . '</span>';
echo ' | ';
$taxonomy = 'pa_Fade';
echo '<span class="attribute-Fade">' . $product->get_attribute($taxonomy) . '</span>';
}
}
解决方法
使用以下重新访问的代码来获取单独的属性值,前提是它们存在于您的可变产品中:
add_action( 'woocommerce_before_shop_loop_item_title','display_some_attributes',5 );
function display_some_attributes() {
global $product;
if ( $product->is_type('variable') ) {
$attributes = array('speed','Glide','Turn','Fade'); // here you defined attribute slugs
$output = array(); // Initializing
// Loop through product attributes
foreach ( $attributes as $attribute ) {
$taxonomy = 'pa_' . $attribute;
$values = $product->get_attribute($taxonomy);
// If not empty add it to the array
if ( ! empty($values) ) {
$output[] = '<span class="attribute-' . $attribute . '">' . $values . '</span>';
}
}
// Convert array to a separated string by pipes
echo implode(' | ',$output);
}
}
要仅定位特定产品类别,请替换代码中的块:
global $product;
if ( $product->is_type('variable') ) {
with (您将在其中定义产品类别术语):
global $product;
$categories = array( 'cats',dogs' ); // Here your category terms ids,slugs or names
if ( $product->is_type('variable') && has_term( $categories,'product_cat',$product->get_id() ) ) {
代码位于活动子主题(或活动主题)的functions.php 文件中。经测试有效。