
我们的目标是在woocommerce购物车页面添加一个复选框,当用户勾选此复选框时,购物车总价应立即应用一个固定的折扣金额;当用户取消勾选时,折扣应被移除。更重要的是,这个折扣状态需要持久化,并在woocommerce的各个环节(如迷你购物车、结算页面、订单详情、后台管理界面及订单邮件)中正确显示和更新。
实现这一功能需要结合前端的HTML/JavaScript和后端的PHP逻辑。前端负责展示复选框并处理用户交互,通过AJAX请求将状态发送到后端;后端则根据状态管理会话数据,并在购物车计算时应用或移除折扣。
首先,我们需要将复选框添加到购物车页面。woocommerce_cart_totals_before_shipping 钩子是一个合适的插入点,它位于购物车总计的运输信息之前。
将以下PHP代码添加到您的主题的 functions.php 文件或自定义插件中:
/**
* 在购物车总计前添加折扣复选框
*/
function custom_add_discount_checkbox_to_cart() {
// 确保在购物车页面且购物车不为空时显示
if ( is_cart() && ! WC()->cart->is_empty() ) {
// 从会话中获取当前折扣状态,用于初始化复选框
$is_discount_applied = WC()->session->get( 'apply_custom_discount', false );
?>
<tr class="custom-discount-row">
<th><?php esc_html_e( '应用特别折扣', 'your-text-domain' ); ?></th>
<td data-title="<?php esc_attr_e( '应用特别折扣', 'your-text-domain' ); ?>">
<label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox">
<input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox"
id="custom_apply_discount"
name="custom_apply_discount"
value="1"
<?php checked( $is_discount_applied, true ); ?> />
<span><?php esc_html_e( '我想要享受固定折扣!', 'your-text-domain' ); ?></span>
</label>
</td>
</tr>
<?php
}
}
add_action( 'woocommerce_cart_totals_before_shipping', 'custom_add_discount_checkbox_to_cart' );代码说明:
复选框的状态变化需要通过AJAX实时更新购物车总计。我们将监听复选框的 change 事件,并向后端发送一个AJAX请求。
将以下JavaScript代码添加到您的主题的JavaScript文件(通常是 theme.js 或 custom.js),或者通过 wp_enqueue_script 钩子将其内联或加载。
jQuery(function($) {
// 监听自定义折扣复选框的改变事件
$(document.body).on('change', '#custom_apply_discount', function() {
var is_checked = $(this).is(':checked');
// 发送AJAX请求到后端
$.ajax({
type: 'POST',
url: woocommerce_params.ajax_url, // WooCommerce提供的AJAX URL
data: {
action: 'custom_update_discount_status', // 后端将处理的AJAX动作
security: woocommerce_params.update_order_review_nonce, // 安全 nonce
apply_discount: is_checked ? 1 : 0
},
success: function(response) {
if (response.success) {
// AJAX成功后,触发购物车/结算页的更新
// 对于购物车页面,触发 'updated_wc_div' 事件
// 对于结算页面,触发 'update_checkout' 事件
if ( $('body').hasClass('woocommerce-cart') ) {
$(document.body).trigger('updated_wc_div');
} else if ( $('body').hasClass('woocommerce-checkout') ) {
$(document.body).trigger('update_checkout');
}
} else {
console.error('更新折扣状态失败:', response.data);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('AJAX请求错误:', textStatus, errorThrown);
}
});
});
});代码说明:
后端需要处理AJAX请求,保存折扣状态到会话,并在购物车计算时应用或移除折扣。
将以下PHP代码添加到您的主题的 functions.php 文件或自定义插件中:
/**
* 1. AJAX处理函数:保存折扣状态到会话
*/
function custom_ajax_update_discount_status() {
// 检查安全 nonce
if ( ! isset( $_POST['security'] ) || ! wp_verify_nonce( $_POST['security'], 'woocommerce-cart' ) && ! wp_verify_nonce( $_POST['security'], 'update-order-review' ) ) {
wp_send_json_error( 'Nonce verification failed.' );
}
$apply_discount = isset( $_POST['apply_discount'] ) && (int) $_POST['apply_discount'] === 1;
// 确保WooCommerce会话已启动
if ( ! WC()->session->has_session() ) {
WC()->session->set_customer_session_cookie( true );
}
// 将折扣状态保存到WooCommerce会话
WC()->session->set( 'apply_custom_discount', $apply_discount );
wp_send_json_success( 'Discount status updated.' );
}
add_action( 'wp_ajax_custom_update_discount_status', 'custom_ajax_update_discount_status' );
add_action( 'wp_ajax_nopriv_custom_update_discount_status', 'custom_ajax_update_discount_status' ); // 允许未登录用户使用
/**
* 2. 应用折扣:使用 woocommerce_cart_calculate_fees 钩子
*/
function custom_apply_fixed_discount_fee( $cart ) {
// 避免在AJAX请求中重复计算
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
// 确保会话已启动
if ( ! WC()->session->has_session() ) {
return;
}
// 获取折扣状态和折扣金额
$is_discount_applied = WC()->session->get( 'apply_custom_discount', false );
$fixed_discount_amount = 10.00; // 设置您的固定折扣金额
if ( $is_discount_applied && $cart->get_subtotal() > 0 ) {
// 添加一个负的费用作为折扣
$cart->add_fee( __( '特别折扣', 'your-text-domain' ), -$fixed_discount_amount, true, 'standard' );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'custom_apply_fixed_discount_fee', 10, 1 );
/**
* 3. 确保WooCommerce会话在所有页面都可用
* 此步骤通常不是必需的,因为WooCommerce默认会启动会话。
* 但如果遇到会话问题,可以尝试。
*/
function custom_start_wc_session() {
if ( ! is_admin() && ! WC()->session->has_session() ) {
WC()->session->set_customer_session_cookie( true );
}
}
add_action( 'init', 'custom_start_wc_session' );代码说明:
AJAX处理函数 (custom_ajax_update_discount_status)
应用折扣函数 (custom_apply_fixed_discount_fee)
会话启动 (custom_start_wc_session)
通过上述步骤,折扣状态已存储在WooCommerce会话中,并在每次购物车计算时被应用。这意味着:
通过上述分步教程,我们成功地在WooCommerce购物车页面集成了一个动态折扣复选框。这个解决方案不仅实现了前端的交互性,还通过后端PHP逻辑确保了折扣的正确应用、持久化以及在WooCommerce生态系统中的全面显示。这种方法为用户提供了灵活的购物体验,同时也为商家提供了一种简便的折扣营销工具。
以上就是WooCommerce购物车页面动态折扣:添加复选框实现固定金额优惠的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号