wordpress 单个Woocommerce产品自定义变体添加到购物车按钮

v8wbuo2f  于 2022-11-22  发布在  WordPress
关注(0)|答案(2)|浏览(199)

我已经自定义了WoCommerce单个产品页面并添加了一个购物车按钮,只需使用这一行

echo woocommerce_simple_add_to_cart();

但现在我需要两个添加的两个购物车按钮的两种类型的变化。我的所有属性和儿童是相同的。类型_的_音频和儿童是mac & windows。
所有我想创建两个自定义添加到购物车链接。但我不能动态配置产品ID。底部是代码。(变量产品ID没有得到正确的,所以它不添加产品到购物车)

<?php if( $product->is_type( 'simple' ) ){                             
   echo woocommerce_simple_add_to_cart();                                
}                          
elseif( $product->is_type( 'variable' ) ){
   echo ('<a href="/?add-to-cart=$variation_id&attribute_pa_type_of_audio=mac">MAC BUTTON</a>');
   echo ('<a href="/?add-to-cart=$variation_id&attribute_pa_type_of_audio=windows">WINDOWS BUTTON</a>');
                                }
?>
svujldwt

svujldwt1#

请尝试以下操作,为每个变体显示一个“添加到购物车”按钮,并带有正确的按钮标签:

<?php 
if ( $product->is_type( 'simple' ) ){
   echo woocommerce_simple_add_to_cart();
}
elseif ( $product->is_type( 'variable' ) ){
    // Loop through available variation data
    foreach ( $product->get_available_variations() as $variation_data ) {
        $url = '?add-to-cart='.$variation_data['variation_id']; // The dynamic variation ID (URL)

        // Loop through variation product attributes data
        foreach ( $variation_data['attributes'] as $attr_key => $term_slug ) {
            // The text button
            if ( $attr_key === 'attribute_pa_type_of_audio' && $term_slug === 'mac' ) 
            { // MAC
                $button_text = __("MAC BUTTON", "woocommerce");
            } elseif  ( $attr_key === 'attribute_pa_type_of_audio' && $term_slug === 'windows' ) 
            { // WINDOWS
                $button_text = __("WINDOWS BUTTON", "woocommerce");
            } else 
            { // OTHER (IF NEEDED)
                $button_text = __("Add to cart", "woocommerce"); 
            }

            $url .= '&'.$attr_key.'='.$term_slug; // Adding the product attribute name with the term value (to Url)
        }
        // Displaying the custom variations add to cart buttons
        if( isset($button_text))
            echo '<a href="'.$url.'" class="button alt">'.$button_text.'</a> ';
    }
}
?>

测试和工程。

qeeaahzv

qeeaahzv2#

if ($product->is_type('simple')) {
    echo woocommerce_simple_add_to_cart();
} elseif ($product->is_type('variable')) {

    $children_ids = $product->get_children();

    foreach ($children_ids as $value) {
        $single_variation = new WC_Product_Variation($value);
        echo '<a href="/?add-to-cart=$variation_id=' . $value . '&attribute_pa_type_of_audio=mac">MAC BUTTON</a>';
    }
}

相关问题