您可以在结帐页面上使用一些基本的 JavaScript 检测所选的付款方式,并通过挂钩使用 PHP 运行您的自定义代码woocommerce_checkout_update_order_review action.
第一的,
您还应该将 JS 代码放置在结帐页面、结帐模板或主题的页眉/页脚中,以便您可以检测用户何时更改了付款方式选项,并在之后运行您自己的代码。
JS code:
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 代码下方添加下一个 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 代码放入 checkout 中,如下所示:
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');
我希望这有帮助!
这是一个非常强大的选项,可以在结帐页面上运行所有自定义逻辑!