我想给wordpress的商店页面添加一些属性。
我在 Stackoverflow 上找到的这段代码显示了所有属性标签,但属性名称相同。
add_action('woocommerce_after_shop_loop_item_title','add_attribute');
function add_attribute() {
global $product;
$product_attributes = array( 'pa_country','pa_class','pa_faction','pa_gender' );
$attr_output = array();
foreach( $product_attributes as $taxonomy ){
if( taxonomy_exists($taxonomy) ){
$label_name = get_taxonomy( $taxonomy )->labels->singular_name;
$value = $product->get_attribute('pa_country','pa_class','pa_faction','pa_gender');
if( ! empty($value) ){
$attr_output[] = '<span class="'.$taxonomy.'">'.$label_name.': '.$value.'</span>';
}
}}
echo '<div class="product-attributes">'.implode( '<br>', $attr_output ).'</div>';
}
当前状态 https://i.stack.imgur.com/zmrE8.png
我只需要一点帮助来让它显示所有正确的属性。
您的代码中有一些小错误。请尝试以下方法:
add_action('woocommerce_after_shop_loop_item_title', 'display_shop_loop_product_attributes');
function display_shop_loop_product_attributes() {
global $product;
// Define you product attribute taxonomies in the array
$product_attribute_taxonomies = array( 'pa_country', 'pa_class', 'pa_faction', 'pa_gender' );
$attr_output = array(); // Initializing
// Loop through your defined product attribute taxonomies
foreach( $product_attribute_taxonomies as $taxonomy ){
if( taxonomy_exists($taxonomy) ){
$label_name = wc_attribute_label( $taxonomy, $product );
$term_names = $product->get_attribute( $taxonomy );
if( ! empty($term_names) ){
$attr_output[] = '<span class="'.$taxonomy.'">'.$label_name.': '.$term_names.'</span>';
}
}
}
// Output
echo '<div class="product-attributes">'.implode( '<br>', $attr_output ).'</div>';
}
代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。
仅对于简单产品,您将使用以下内容:
add_action('woocommerce_after_shop_loop_item_title', 'display_shop_loop_product_attributes');
function display_shop_loop_product_attributes() {
global $product;
// Only for simple products
if ( ! $product->is_type( 'simple' ) ) return;
// Define you product attribute taxonomies in the array
$product_attribute_taxonomies = array( 'pa_country', 'pa_class', 'pa_faction', 'pa_gender' );
$attr_output = array(); // Initializing
// Loop through your defined product attribute taxonomies
foreach( $product_attribute_taxonomies as $taxonomy ){
if( taxonomy_exists($taxonomy) ){
$label_name = wc_attribute_label( $taxonomy, $product );
$term_names = $product->get_attribute( $taxonomy );
if( ! empty($term_names) ){
$attr_output[] = '<span class="'.$taxonomy.'">'.$label_name.': '.$term_names.'</span>';
}
}
}
// Output
echo '<div class="product-attributes">'.implode( '<br>', $attr_output ).'</div>';
}
代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)