在Woocommerce Archives上显示可变产品属性和术语

问题描述 投票:2回答:1

我正在尝试使用钩子woocommerce_shop_loop_item_title在商店页面上完成属性和术语列表。目标是获取产品的属性和术语,然后像这个示例一样显示它:

颜色:红色,蓝色,绿色

尺寸:小,中,大

尺寸:90 * 90,100 * 100和120 * 120

但没有行之间的空格。

它应该“获取”产品使用的所有属性和属性术语。

我试过这个,但是发生了致命的错误。

add_action( 'woocommerce_shop_loop_item_title', 'variable_att_and_terms_on_loop');
function variable_att_and_terms_on_loop() {

    foreach( $product->get_variation_attributes() as $taxonomy => $terms_slug ) {

    $taxonomy_label = wc_attribute_label( $taxonomy, $product );

    foreach($terms_slug as $term) {
        $term_name  = get_term_by('slug', $term, $taxonomy)->name;
        $attributes_and_terms_names[$taxonomy_label][$term] = $term_name;
    }
}
foreach ( $attributes_and_terms_names as $attribute_name => $terms_name ) {
    $terms_string = implode( ', ', $terms_name );
    echo '<p>' . $attribute_name . ': ' . $terms_string . '</p>';
}
}

我也试过这个:

add_action('woocommerce_shop_loop_item_title','add_attribute', 5);
function add_attribute() {
    global $product;

    $product_attributes = array( 'pa_weight', 'pa_quantity', 'pa_length', 'pa_color' );
    $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_weight');

            if( ! empty($value) ){
                $attr_output[] = '<span class="'.$taxonomy.'">'.$label_name.': '.$value.'</span>';
            }
        }
    }
    echo '<div class="product-attributes">'.implode( '<br>', $attr_output ).'</div>';
}

没有任何结果。在从LoicTheAztec尝试下面的新结果之后,这就是我得到的:enter image description here

php wordpress woocommerce custom-taxonomy taxonomy-terms
1个回答
1
投票

在您的第一个代码段中有一些错误:

  • $product变量未定义
  • 该功能仅限于可变产品
  • $attributes_and_terms_names变量未初始化...

这是重新访问的代码(没有行之间的空格):

add_action( 'woocommerce_shop_loop_item_title', 'variable_att_and_terms_on_loop');
function variable_att_and_terms_on_loop() {
    global $product;

    if( ! $product->is_type('variable') ) return; // Only for variable products

    $variation_attributes = $product->get_variation_attributes();

    if( sizeof($variation_attributes ) == 0 ) return; // Exit if empty

    $attributes = array(); // Initializing

    foreach( $product->get_variation_attributes() as $taxonomy => $terms_slug ) {
        $taxonomy_label = wc_attribute_label( $taxonomy, $product );

        $terms_name = array();

        foreach($terms_slug as $term) {
            $terms_name[] = get_term_by('slug', $term, $taxonomy)->name;
        }
        $attributes[] = $taxonomy_label . ':&nbsp;' . implode( ', ', $terms_name );
    }

    echo '<div class="product-attributes">';
    echo '<span>' . implode('</span><br><span>', $attributes) . '</span>';
    echo '</div>';
}

代码位于活动子主题(活动主题)的function.php文件中。经过测试和工作。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.