Php 在产品循环中显示特定类别的产品属性值
我正在WP+WooCommerce建一家商店。我有不同类型的产品类别,如光盘和包。对于光盘产品,我有一些特定的属性,如速度、滑动、旋转和褪色,这些属性没有任何其他产品类别。我只想在产品图片下的商店页面上显示这些产品属性值 我已经找到了一个代码,我给自己添加了一个分隔符号“|”,但是这个分隔符号现在显示在所有可变产品下 是否可以不将代码更改为变量,而仅更改特定产品类别和子类别的代码 代码:Php 在产品循环中显示特定类别的产品属性值,php,wordpress,woocommerce,product,taxonomy-terms,Php,Wordpress,Woocommerce,Product,Taxonomy Terms,我正在WP+WooCommerce建一家商店。我有不同类型的产品类别,如光盘和包。对于光盘产品,我有一些特定的属性,如速度、滑动、旋转和褪色,这些属性没有任何其他产品类别。我只想在产品图片下的商店页面上显示这些产品属性值 我已经找到了一个代码,我给自己添加了一个分隔符号“|”,但是这个分隔符号现在显示在所有可变产品下 是否可以不将代码更改为变量,而仅更改特定产品类别和子类别的代码 代码: add_action('woocommerce_-before_-shop_-loop_-item_-ti
add_action('woocommerce_-before_-shop_-loop_-item_-title','display_-size_-attribute',5);
函数显示\大小\属性(){
全球$产品;
如果($product->is_类型('variable')){
$taxonomy='pa_speed';
回显“”。$product->get_属性($taxonomy)。“”;
回音“|”;
$taxonomy='pa_Glide';
回显“”。$product->get_属性($taxonomy)。“”;
回音“|”;
$taxonomy='pa_Turn';
回显“”。$product->get_属性($taxonomy)。“”;
回音“|”;
$taxonomy='pa_Fade';
回显“”。$product->get_属性($taxonomy)。“”;
}
}
仅当变量产品上存在单独的属性值时,使用以下重新访问的代码来获取它们:
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);
}
}
使用(您将在其中定义产品类别术语):
代码进入活动子主题(或活动主题)的functions.php文件。已测试并正常工作。我的代码显示所有非空属性值,包括“0”,因为我使用
empty()
所以null
或'
(空字符串)…感谢您的支持。一切都很好,但是如果它是0(零),它就不会显示值。例如,我将属性“Turn”设置为0,但它不显示。屏幕截图-如果你想说些什么,如果你想让我得到通知,在我的答案下面的评论区添加一条评论。
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') ) {
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() ) ) {