WooCommerce: check if product has attribute

只谈情不闲聊 提交于 2020-07-08 21:33:30

问题


I'm trying to append text to products that cointain the attribute "pa_sprog" value "dansk"

I am working from this post this is what I have so far:

add_action( 'woocommerce_before_add_to_cart_form', 'flag1' );    
function flag1() {
    $product = wc_get_product( $product_id );

    // Get the product attribute value
    $sprog = $product->get_attribute('pa_sprog');

    // if product has attribute 'sprog' value(s)
    if( $sprog="dansk" ){
        echo '<div class="">"Dansk!"</div>';
    } else {
        // Engelsk
    }
}

回答1:


Give it a try this way, I left the code to debug, so that you can view the WC_Product_Attribute Object in detail. Afterwards you can safely remove this

function flag1() {
    global $product;

    // for debug purposes, place in comment tags or delete this code
    $product_attributes = $product->get_attributes();
    echo '<pre>', print_r($product_attributes, 1), '</pre>';

    // Get the product attribute value
    $sprog = $product->get_attribute('pa_sprog');

    // if product has attribute 'sprog' value(s)
    if( $sprog == "dansk" ) {
        echo '<div class="">Dansk!</div>';
    } else {
        echo '<div class="">Engelsk!</div>';
    }
}
add_action( 'woocommerce_before_add_to_cart_form', 'flag1' );


来源:https://stackoverflow.com/questions/60290411/woocommerce-check-if-product-has-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!