Last active
September 12, 2022 08:06
-
-
Save nczz/9f30487248e0446e827e4fc537b0fde4 to your computer and use it in GitHub Desktop.
WooCommerce 商品快速結帳按鈕
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function mxp_woocommerce_after_add_to_cart_button(){ | |
global $woocommerce; | |
$checkout_url = $woocommerce->cart->get_checkout_url(); | |
echo '<div id="ks_quick_checkout"><a href="'.$checkout_url.'?add-to-cart='.get_queried_object_id().'" class="button alt">直接結帳</a></div>'; | |
?> | |
<script> | |
jQuery(document).ready(function() { | |
var v_product = jQuery('form.variations_form.cart').data(); | |
if (v_product === undefined) { | |
return; | |
} | |
var p_vdata = v_product.product_variations; | |
var p_id = v_product.product_id; | |
var v_pricing_key = []; | |
for (var i = 0; i < p_vdata.length; i++) { | |
var e = p_vdata[i]; | |
var attrs = e.attributes; | |
var v_id = e.variation_id; | |
var subkey = []; | |
for (var key in attrs) { | |
var index = key; | |
var data = attrs[key]; | |
if (data != "") { | |
vpush = { v_id: v_id, v_v: data, v_key: index, p_id: p_id }; | |
} else { | |
subkey.push(index); | |
} | |
} | |
vpush.sub = subkey; | |
v_pricing_key.push(vpush); | |
} | |
// console.log(v_pricing_key); | |
jQuery('#ks_quick_checkout>a').attr('href', 'javascript:'); | |
jQuery('#ks_quick_checkout').click(function() { | |
//掃描現在的選擇 | |
for (var i = 0; i < v_pricing_key.length; i++) { | |
var v = v_pricing_key[i]; | |
if (jQuery('select[name="' + v.v_key + '"]').val() == "") { | |
alert('請先選擇項目!'); | |
return; | |
} | |
if (jQuery('select[name="' + v.v_key + '"]').val() == v.v_v) { | |
var vkey = decodeURI(v.v_key.split('_').join('_pa_')); | |
var checkout_url = '/checkout/?add-to-cart=' + v.p_id + '&variation_id=' + v.v_id + '&' + vkey + '=' + encodeURI(v.v_v) + '&'; | |
for (var j = 0; j < v.sub.length; j++) { | |
var other_attr = v.sub[j]; | |
if (jQuery('select[name="' + other_attr + '"]').val() == "") { | |
alert('請先選擇項目!'); | |
return; | |
} | |
checkout_url += decodeURI(other_attr.split('_').join('_pa_')) + '=' + encodeURI(jQuery('select[name="' + other_attr + '"]').val()); | |
} | |
// console.log(checkout_url); | |
} | |
} | |
var form = jQuery('form.variations_form.cart'); | |
form.attr('action', '/checkout/'); | |
form.submit(); | |
}); | |
}); | |
</script> | |
<?php | |
} | |
add_action('woocommerce_after_add_to_cart_button','mxp_woocommerce_after_add_to_cart_button'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ref: WooCommerce Custom “Add to Cart” URLs – The Ultimate Guide