[英]Single Woocommerce product custom variations add to cart buttons
I have customized WoCommerce single product page and added a cart button using simply this line我已经自定义了WoCommerce 单个产品页面并使用此行添加了一个购物车按钮
echo woocommerce_simple_add_to_cart();
but now I need two added two cart button for two types of variation.但现在我需要为两种类型的变化添加两个购物车按钮。 My all attribute and child is same.我的所有属性和孩子都是一样的。 type_of_audio and child is mac & windows. type_of_audio 和 child 是 mac 和 windows。
All I want to create two custom add to cart link.我只想创建两个自定义添加到购物车链接。 but I cannot configure the product id dynamically.但我无法动态配置产品 ID。 bottom is the code.底部是代码。 (Variable product id is not getting properly so it's not adding product to cart) (可变产品 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>');
}
?>
Try the following that will display an add to cart button for each variation with the correct button label:尝试以下操作,将为每个变体显示一个添加到购物车的按钮,并带有正确的按钮标签:
<?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> ';
}
}
?>
Tested and works.测试和工作。
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>';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.