在 Woocommerce 变量产品中显示基于产品属性的自定义文本

Display a custom text based on product attributes in Woocommerce variable product

我正在尝试根据当前产品的选项在可变产品页面上显示文本。 比如说,如果这个产品带有(属性)选项#1,那么显示文本#1, 如果此产品提供(属性)选项#2,则显示文本#2

我已经尝试了以下代码,但无论可用的属性如何,所有可变产品都会显示 text#1 和 text#2。

add_action('woocommerce_single_product_summary', 'display_custom_meta_field_value', 25 );
function display_custom_meta_field_value() {
    global $product;

    if ( $product->is_type( 'variable' ) ) {

        if (wc_attribute_taxonomy_name ('valve-options-white')  == 'pa_valve-options-white' ) 
        echo  '<p id="value-on-single-product"><i class="fas fa-info-circle"></i><a href="#" class="popmake-1087"> Which Valves Do I Need? CLICK HERE</a></p>';

        if ( (wc_attribute_taxonomy_name ('valve-options-chrome') ) == ('pa_valve-options-chrome') )
        echo  '<p id="value-on-single-product"><i class="fas fa-info-circle"></i><a href="#" class="popmake-697"> Which Valves Do I Need? CLICK HERE</a></p>';
    }
}

我只想根据分配的属性(组)为每个可变产品显示文本#1 或文本#2 之一。 谢谢。

您应该使用 WC_Product_Variable get_variation_attributes() 方法尝试以下操作:

add_action('woocommerce_single_product_summary', 'display_custom_meta_field_value', 25 );
function display_custom_meta_field_value() {
    global $product;

    if ( $product->is_type( 'variable' ) ) {
        // Loop through variations attributes
        foreach($product->get_variation_attributes() as $taxonomy => $term_slugs ) {
            if( $taxonomy === 'pa_valve-options-white' ) {
                $popmake_id = '1087';
            } elseif( $taxonomy === 'pa_valve-options-chrome' ) {
                $popmake_id = '697';
            }
        }

        if ( isset($popmake_id) ) {
            $text = __( "Which Valves Do I Need? CLICK HERE","woocommerce" );
            echo '<p id="value-on-single-product"><i class="fas fa-info-circle"></i><a href="#" class="popmake-'.$popmake_id.'"> '.$text.'</a></p>';
        }
    }
}

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