WooCommerce技术实现:如何获取自定义属性标签并在函数中使用
WooCommerce产品属性标签动态替换实现
我编写了代码用于获取名为Model的自定义产品属性值,并在div表格中展示。原本用静态文本作为属性标签,想要替换为系统对应的属性标签;同时创建了短码display-attributes-algemeen,方便在站点指定位置调用,还添加了属性为空时不展示的判断逻辑。
最初尝试使用wc_attribute_label()或get_taxonomy()函数,但不知道如何正确实现。后来通过修改代码解决了问题:在获取属性值后添加$model_label = wc_attribute_label('pa_model'),再将静态文本标签替换为该变量,就成功实现了属性标签的动态展示。
原代码
add_shortcode( 'display-attributes-algemeen', 'get_product_attributes_shortcode' ); function get_product_attributes_shortcode( $atts ) { extract( shortcode_atts( array( 'id' => get_the_ID(), ), $atts, 'display-attributes-algemeen' ) ); global $product; if ( ! is_a($product, 'WC_Product') ) { $product = wc_get_product( $id ); } if ( is_a($product, 'WC_Product') ) { $model = $product->get_attribute('Model'); if ( $model ) { $output = '<span class="specstitel">Algemeen</span><div class="divTableAtt LichtBlauweRegels"> <div class="divTableAttBody">'; if ( $model ) { $output .= '<div class="divTableAttRow"> <div class="divTableAttCell">Model</div> <div class="divTableAttCell">' . $model . '</div> </div>'; } return $output . '</div></div>'; } } }
修改后的关键代码片段
首先是属性标签获取部分:
if ( is_a($product, 'WC_Product') ) { $model = $product->get_attribute('Model'); $model_label = wc_attribute_label('pa_model');
然后是标签替换部分:
if ( $model ) { $output .= '<div class="divTableAttRow"> <div class="divTableAttCell">' . $model_label . '</div> <div class="divTableAttCell">' . $model . '</div> </div>';
内容的提问来源于stack exchange,提问作者John Roeland
相关产品推荐
相关产品推荐

