显示 WooCommerce 自定义产品属性和单个产品的所有术语

我使用自定义函数在 WooCommerce 单一产品页面上创建了六个自定义属性。它们包括:图标、标签和术语。

基于将 WooCommerce 属性标签替换为每个答案代码的自定义图像,我使用了以下函数(使用自定义 HTML 标记,与 WooCommerce Product-attributes.php 模板中的标记不同)

add_action('woocommerce_single_product_summary', 'pa_custom_attributes', 25);

function pa_custom_attributes(){

    global $product;


    $attributes = $product->get_attributes();


    if ( ! $attributes ) return;


    $out = '<div class="custom-attributes">';


    foreach ( $attributes as $attribute ) {


        if ( $attribute->get_variation() ) continue;


        if ( $attribute->is_taxonomy() ) {

            

            $taxonomy = $attribute->get_name();

            $taxo_obj = $attribute->get_taxonomy_object();

            $name = $taxo_obj->attribute_name;

            $label = $taxo_obj->attribute_label;

            $label_name = wc_attribute_label( $taxonomy );


            $out .= '<div class="' . esc_attr( $taxonomy ) . ' single-attribute">';


            $out .= '<div><img class="attribute-image" src="'.get_stylesheet_directory_uri().'/woocommerce/attributes/'.$name.'.svg" alt="Attribute '.$label.'"/></div>';


            $out .= '<div class="attribute-label '.$label.'">'.$label_name.'</div>';

            

            $out .= '<div class="attribute-values">';


            $terms = wp_get_post_terms( $product->get_id(), $taxonomy, array('fields' => 'names') );


            foreach ( $terms as $term_name )

                $term_names['names'] = $term_name;


            $out .= implode(', ', $term_names);

            $out .= '</div></div>';


        } 


该函数工作正常,但有一个问题:如果特定属性的项超过一个(例如颜色:红色、蓝色、绿色),则该函数在屏幕上仅打印数组的最后一个值。


我阅读了文档并做了很多测试,检查CSS没有问题。


有谁可以帮我理解错误出在哪里吗?


拉丁的传说
浏览 162回答 1
1回答

侃侃尔雅

问题来自于您的代码中的以下内容:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $terms = wp_get_post_terms( $product->get_id(), $taxonomy, array('fields' => 'names') );&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach ( $terms as $term_name )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $term_names['names'] = $term_name;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $out .= implode(', ', $term_names);你可以用这个替换:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $terms = wp_get_post_terms( $product->get_id(), $taxonomy, array('fields' => 'names') );&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $term_names = []; // Initializing&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Loop through each terms&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach ( $terms as $term_name ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $term_names[] = $term_name;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $out .= implode(', ', $term_names);或者用一行代码就更好了:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $out .= $product->get_attribute( $taxonomy );
打开App,查看更多内容
随时随地看视频慕课网APP