您可以使用结帐页面上的一些基本 JavaScript 检测所选的付款方式,并通过挂钩到 woocommerce_checkout_update_order_review 操作使用 PHP 运行您的自定义代码。
首先,
您还应该将 JS 代码放在结帐页面、结帐模板或主题的页眉/页脚中,以便您可以检测用户何时更改了付款方式选项并在此之后运行您自己的代码。
JS代码:
jQuery(document).ready( function() {
jQuery( "#payment_method_bacs" ).on( "click", function() {
jQuery( 'body' ).trigger( 'update_checkout' );
});
jQuery( "#payment_method_paypal" ).on( "click", function() {
jQuery(document.body).trigger("update_checkout");
});
jQuery( "#payment_method_stripe" ).on( "click", function() {
jQuery(document.body).trigger("update_checkout");
});
});
请注意,对于您启用的每种付款方式,您都应该添加“点击”事件。它使您可以选择在触发自定义代码时进行微调。
为了防止点击事件只运行一次,你应该在第一个下面添加下一个 JS 代码块。
jQuery( document ).ajaxStop(function() {
jQuery( "#payment_method_bacs" ).on( "click", function() {
jQuery(document.body).trigger("update_checkout");
});
jQuery( "#payment_method_paypal" ).on( "click", function() {
jQuery(document.body).trigger("update_checkout");
});
jQuery( "#payment_method_stripe" ).on( "click", function() {
jQuery(document.body).trigger("update_checkout");
});
});
这只是在 ajax 之后触发的相同代码。
在这两个 JS 代码块中添加您您实际使用的付款选项。
之后,您将挂钩到结帐的自定义 PHP 代码如下所示:
if ( ! function_exists( 'name_of_your_function' ) ) :
function name_of_your_function( $posted_data) {
// Your code goes here
}
endif;
add_action('woocommerce_checkout_update_order_review', 'name_of_your_function');
这段代码可以放在functions.php中。
这是在结帐页面上选择特定付款选项时检测并运行的完整 PHP 代码:
function name_of_your_function( $posted_data) {
global $woocommerce;
// Parsing posted data on checkout
$post = array();
$vars = explode('&', $posted_data);
foreach ($vars as $k => $value){
$v = explode('=', urldecode($value));
$post[$v[0]] = $v[1];
}
// Here we collect payment method
$payment_method = $post['payment_method'];
// Run code custom code for each specific payment option selected
if ($payment_method == "paypal") {
// Your code goes here
}
elseif ($payment_method == "bacs") {
// Your code goes here
}
elseif ($payment_method == "stripe") {
// Your code goes here
}
}
add_action('woocommerce_checkout_update_order_review', 'name_of_your_function');
我希望这会有所帮助!
这是在结帐页面上运行所有自定义逻辑的非常强大的选项!