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

时间:2019-02-22 10:40:53

标签: php wordpress woocommerce variations taxonomy-terms

我已自定义 WoCommerce单一产品页面,并仅使用此行添加了购物车按钮

echo woocommerce_simple_add_to_cart();

但是现在我需要为两个类型的变体添加两个购物车按钮。我的所有属性和孩子都是相同的。 type_of_audio和child是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>');
                                }
?>

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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

经过测试可以正常工作。

相关问题