Creating custom add to cart button for variable products with variations in WooCommerce

I’m trying to create a custom button for products that have variations in WooCommerce.

For context, In WooCommerce, I have a product attribute called “License Type”. This attribute has 2 terms:

  1. Single Site License,
  2. Multi Site License.

I have a product (with an ID of 203), which contains these two variations:

In my theme, I have an override for content-single.product.php template, where I have the following snippets:

  1. The select dropdown for a user to determine which license they want:
<?php

global $product;

if ($product->is_type('variable')) :

  $taxonomy = 'pa_license_type';
  $terms = array();

  foreach ($product->get_children() as $variation_id) :
    $variation = wc_get_product($variation_id);

    if (!$variation) :
      continue;
    endif;

    // Get the attribute value for the specified taxonomy
    $attribute_value = $variation->get_attribute($taxonomy);

    if ($term = get_term_by('slug', esc_html($attribute_value), $taxonomy)) :
      $terms[$variation->get_id()] = $term;
    endif;

  endforeach;

  if (count($terms) > 0) :
    printf('<label for="%s">%s</label><select name="%s" id="%s">', esc_attr($taxonomy), wc_attribute_label($taxonomy), esc_attr($taxonomy), esc_attr($taxonomy));
    foreach ($terms as $variation_id => $term) :
      printf('<option value="%s" data-variation-id="%d">%s</option>', esc_attr($term->slug), $variation_id, esc_html($term->name));
    endforeach;
    echo '</select>';
  endif;

endif;

?>
  1. The custom button markup:
<?php if ( $product  && $product->is_in_stock() ) :

  $product_id = $product->get_id();
  $add_to_cart_url = esc_url( '?add-to-cart=' . $product_id . '&redirect_to_cart=1' );

  if ($product->is_type('variable')) : ?>
    <a id="variationBtn" href="<?= $add_to_cart_url; ?>">
      <?php _e( 'Add to Cart (Variation)', 'woocommerce' ); ?>
    </a>
  <?php else: ?>
    <a href="<?= $add_to_cart_url; ?>">
      <?php _e( 'Add to Cart', 'woocommerce' ); ?>
    </a>
  <?php endif; ?>

<?php endif; ?>
  1. The JS that controls the href on the variation button based on the variation ID of the selected license from the dropdown:
document.addEventListener('DOMContentLoaded', function() {
  const variationBtn = document.getElementById('variationBtn');
  const licenseTypeSelect = document.getElementById('pa_license_type');

  function updateAddToCartUrl() {
    const selectedOption = licenseTypeSelect.options[licenseTypeSelect.selectedIndex];
    const selectedLicenseType = selectedOption.value;
    const variationId = selectedOption.getAttribute('data-variation-id');

    const addToCartUrl = `?add-to-cart=<?php echo $product_id; ?>&variation_id=${variationId}&attribute_pa_license-type=${selectedLicenseType}&redirect_to_cart=1`;
    variationBtn.setAttribute('href', addToCartUrl);
  }

  // Init on page load with default values
  updateAddToCartUrl();

  // Update the URL when the license type changes
  licenseTypeSelect.addEventListener('change', updateAddToCartUrl);
});

E.g A sample rendered HTML view of my button:

<a id="variationBtn" href="?add-to-cart=203&variation_id=211&attribute_pa_license-type=single-site-license&redirect_to_cart=1">Add to Cart (Variation)</a>

The desired functionality

  1. User selects license type from dropdown
  2. User clicks on add to cart button
  3. System recognises which variation to add to the cart from the product and variation ID
  4. User is redirected to cart automatically

The current results

Step 3 is where my approach isn’t working.

My button href successfully updates with the variation ID on change etc. But, on click of the button, it doesn’t add my product to the cart.

First, there are some small changes to make in your 2nd code snippet:

<?php if ( $product  && $product->is_in_stock() ) :
    $product_id      = $product->get_id();
    $add_to_cart_url = esc_url( '?add-to-cart=' . $product_id . '&redirect_to_cart=1' );
  
    if ($product->is_type('variable')) {
        printf('<a id="variationBtn" data-product_id="%d" href="%s">%s</a>', $product_id, $add_to_cart_url, __('Add to Cart (Variation)', 'woocommerce'));
    } else {
        printf('<a href="%s">%s</a>', $add_to_cart_url, __('Add to Cart', 'woocommerce') );
    } ?>
<?php endif;?>

Then there are multiple mistakes in your JavaScript code (here I use jQuery as this JS library is used by WordPress and WooCommerce). Try the following instead:

jQuery(function($){
    if ( $('#variationBtn').length ) {
        const taxonomy = 'pa_license_type', 
            productID  = $('#variationBtn').data('product_id');

        var variationID = $('select[name='+taxonomy+']').find(":selected").data('variation-id'),
            selectedVal = $('select[name='+taxonomy+']').find(":selected").val();

        function changeAddToCartURL(){
            const addToCartUrl = '?add-to-cart='+productID+'&variation_id='+variationID+'&attribute_'+taxonomy+'='+selectedVal+'&redirect_to_cart=1';
            $('#variationBtn').attr('href', addToCartUrl);
        }

        // At start
        changeAddToCartURL();

        // On Change
        $('select[name='+taxonomy+']').on('change', function(){
            variationID = $(this).find(":selected").data('variation-id'),
            selectedVal = $(this).find(":selected").val();
            changeAddToCartURL();
        });
    }
});

Now you will be able adding to cart the selected variation (license type).

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật