
在woocommerce商店中,为用户提供额外的折扣选项可以有效提升转化率。本教程将引导您实现一个功能,即在购物车页面添加一个复选框,允许用户选择是否应用一个预设的固定金额折扣。此方案确保折扣能实时更新并正确反映在整个购物流程中,包括迷你购物车、结算页、订单邮件,并能在管理员后台的订单详情中清晰展示。
首先,我们需要在购物车总计区域添加一个复选框。这可以通过使用WooCommerce提供的woocommerce_cart_totals_before_shipping动作钩子来实现。
将以下代码添加到您的主题的functions.php文件或自定义插件中:
/**
* 1. 在购物车总计区域添加自定义折扣复选框
*/
add_action('woocommerce_cart_totals_before_shipping', 'my_custom_discount_checkbox');
function my_custom_discount_checkbox() {
// 检查当前会话中是否已应用折扣,以保持复选框状态
$checked = WC()->session->get('apply_fixed_discount') ? 'checked' : '';
// 输出复选框的HTML结构
echo '<tr class="discount-checkbox-row">';
echo '<th><label for="apply_fixed_discount">' . __('应用固定折扣', 'your-text-domain') . '</label></th>';
echo '<td data-title="' . __('应用固定折扣', 'your-text-domain') . '">';
echo '<input type="checkbox" id="apply_fixed_discount" name="apply_fixed_discount" value="1" ' . $checked . '>';
echo '</td>';
echo '</tr>';
}代码解释:
接下来,我们需要在后端根据复选框的状态来实际应用或移除折扣。我们将使用woocommerce_cart_calculate_fees钩子来添加一个负数费用(即折扣)。
/**
* 2. 根据会话变量应用/移除固定折扣
*/
add_action('woocommerce_cart_calculate_fees', 'my_apply_fixed_discount_fee', 10, 1);
function my_apply_fixed_discount_fee($cart) {
// 避免在管理后台或非AJAX请求中重复计算
if (is_admin() && !defined('DOING_AJAX')) {
return;
}
// 检查会话中是否设置了应用折扣的标志
if (WC()->session->get('apply_fixed_discount')) {
$fixed_discount_amount = 20; // 定义您的固定折扣金额,例如20元
// 添加一个负数费用作为折扣
$cart->add_fee(__('固定折扣', 'your-text-domain'), -$fixed_discount_amount, true, 'discount');
}
}代码解释:
为了实现用户选中/取消选中复选框时实时更新购物车总计,我们需要使用JavaScript监听复选框的变化,并通过AJAX请求将状态发送到后端。
首先,我们需要注册并加载我们的JavaScript文件。
/**
* 3.1 注册并加载JavaScript文件
*/
add_action('wp_enqueue_scripts', 'my_enqueue_discount_checkbox_script');
function my_enqueue_discount_checkbox_script() {
// 仅在购物车和结算页面加载脚本
if (is_cart() || is_checkout()) {
// 确保您的JS文件位于主题或插件的 /js/ 目录下
wp_enqueue_script('discount-checkbox-script', plugins_url('/js/discount-checkbox.js', __FILE__), array('jquery', 'wc-cart'), null, true);
// 将AJAX URL和nonce传递给JavaScript
wp_localize_script('discount-checkbox-script', 'my_ajax_object', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('discount_checkbox_nonce') // 创建一个安全nonce
));
}
}代码解释:
在您的主题或插件的js文件夹中创建discount-checkbox.js文件,并添加以下内容:
jQuery(document).ready(function($) {
// 监听复选框的change事件
$(document.body).on('change', '#apply_fixed_discount', function() {
var isChecked = $(this).is(':checked'); // 获取复选框的当前状态
// 发送AJAX请求到后端
$.ajax({
type: 'POST',
url: my_ajax_object.ajax_url, // 从wp_localize_script获取AJAX URL
data: {
action: 'update_discount_checkbox_state', // 后端处理的动作名称
apply_discount: isChecked,
nonce: my_ajax_object.nonce // 安全nonce
},
success: function(response) {
if (response.success) {
// 触发WooCommerce的购物车更新事件,刷新购物车片段
$(document.body).trigger('wc_update_cart');
console.log('折扣复选框状态已更新,购物车已刷新。');
} else {
console.error('AJAX Error:', response.data);
}
},
error: function(xhr, status, error) {
console.error('AJAX Request Failed:', status, error);
}
});
});
});代码解释:
最后,我们需要在后端创建一个PHP函数来处理来自JavaScript的AJAX请求。此函数将更新会话中的折扣状态,并重新计算购物车总计。
/**
* 4. 后端AJAX处理函数:更新会话中的折扣状态
*/
add_action('wp_ajax_update_discount_checkbox_state', 'my_update_discount_checkbox_state_callback');
add_action('wp_ajax_nopriv_update_discount_checkbox_state', 'my_update_discount_checkbox_state_callback');
function my_update_discount_checkbox_state_callback() {
// 安全验证:检查nonce
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'discount_checkbox_nonce')) {
wp_send_json_error('权限不足!'); // 返回错误信息
}
$apply_discount = isset($_POST['apply_discount']) && $_POST['apply_discount'] === 'true';
// 更新会话变量
WC()->session->set('apply_fixed_discount', $apply_discount);
// 重新计算购物车总计,以便后续wc_update_cart能获取到正确的数据
WC()->cart->calculate_totals();
wp_send_json_success(); // 返回成功响应
}代码解释:
以上就是在WooCommerce购物车页面添加折扣复选框并应用固定折扣的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号