0
votes

I am trying display text on variable product page depending on current product's options. Say, if this product comes with (attributes) options#1 then display text#1, if this product is offered with (attributes) options#2 then display text#2

I have tried the following code but both text#1 and text#2 display for all variable products regardless of what attributes available.

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>';
    }
}

I want only one of text#1 or text#2 displayed for each variable product depending on what attributes (group) has been assigned. Thank you.

1

1 Answers

1
votes

You should try the following instead using WC_Product_Variable get_variation_attributes() method:

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>';
        }
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.