【发布时间】:2019-06-23 12:09:30
【问题描述】:
我正在尝试 LoicTheAztec 的以下代码 - Add to cart and redirect to checkout for variable products in WooCommerce
现在,问题是每当我在产品编辑器中设置默认变体的情况下单击“立即购买”按钮时,代码都无法正常工作。
在这种情况下,“立即购买”网址变为 …/?addtocart=0&quantity=n
我正在使用的主题 - 巴塞尔
有什么解决办法吗?
尝试了 LoicTheAztec 的代码。
function add_custom_addtocart_and_checkout() {
global $product;
$addtocart_url = wc_get_checkout_url().'?add-to-cart='.$product->get_id();
$button_class = 'single_add_to_cart_button button alt custom-checkout-btn';
$button_text = __("Buy & Checkout", "woocommerce");
if( $product->is_type( 'simple' )) :
?>
<script>
jQuery(function($) {
var url = '<?php echo $addtocart_url; ?>',
qty = 'input.qty',
button = 'a.custom-checkout-btn';
// On input/change quantity event
$(qty).on('input change', function() {
$(button).attr('href', url + '&quantity=' + $(this).val() );
});
});
</script>
<?php
elseif( $product->is_type( 'variable' ) ) :
$addtocart_url = wc_get_checkout_url().'?add-to-cart=';
?>
<script>
jQuery(function($) {
var url = '<?php echo $addtocart_url; ?>',
vid = 'input[name="variation_id"]',
pid = 'input[name="product_id"]',
qty = 'input.qty',
button = 'a.custom-checkout-btn';
// Once DOM is loaded
setTimeout( function(){
if( $(vid).val() != '' ){
$(button).attr('href', url + $(vid).val() + '&quantity=' + $(qty).val() );
}
}, 300 );
// On input/change quantity event
$(qty).on('input change', function() {
if( $(vid).val() != '' ){
$(button).attr('href', url + $(vid).val() + '&quantity=' + $(this).val() );
}
});
// On select attribute field change event
$('.variations_form').on('change blur', 'table.variations select', function() {
if( $(vid).val() != '' ){
$(button).attr('href', url + $(vid).val() + '&quantity=' + $(qty).val() );
}
});
});
</script>
<?php
endif;
echo '<a href="'.$addtocart_url.'" class="'.$button_class.'">'.$button_text.'</a>';
} ```
I expect this code to work when the user does not change or update any variations on the product page. That is when the user clicks on the Buy Now button with the default variations.
【问题讨论】:
标签: php wordpress woocommerce