在 WooCommerce 变体价格上显示特定的所选产品属性

Display specific the selected product attribute on the WooCommerce variation price

我想在 .

我找到了很多代码,它们甚至都可以工作,但是所有这些代码 return 都是所有可用属性的列表。

add_action( 'woocommerce_before_variations_form', 'display_attribute', 5 );
function display_attribute(){
    global $product;
    $output = array();
    if( $verpackung = $product->get_attribute('pa_verpackung') ){
        echo $verpackung;
        $output[] = $verpackung;
    }
}

这是一个可变产品,我想显示包装的大小,这是一个属性。例如:€ 39,- 一盒 300g。

以下将在选择的变化价格(在可变产品上)之后显示相应的包装类型,例如:"€ 39,- for a box of 300g"

add_filter( 'woocommerce_available_variation', 'set_packaging_type_after_variation_price', 10, 3 );
function set_packaging_type_after_variation_price( $data, $product, $variation ) {
    $targeted_taxonomy  = 'pa_verpackung'; // <== Define here the product attribute taxonomy

    // Loop through variation attributes
    foreach( $data['attributes'] as $variation_attribute => $term_slug ) {
        $attribute_taxonomy = str_replace( 'attribute_', '', $variation_attribute ); // Get product attribute the taxonomy

        // For matching variation attribute …
        if ( $attribute_taxonomy == $targeted_taxonomy ){
            $verpackung  = get_term_by( 'slug', $term_slug, $attribute_taxonomy )->name; // Get the term name
            $verpackung = ' <span class="verpackung">'. __('für eine '). $verpackung .'</span></span>';
            // Set the "packaging" after the selected viariation price
            $data['price_html'] = str_replace( '</span></span>', '</span>' . $verpackung, $data['price_html'] );
            break; // Stop the loop
        }
    }
    return $data;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。