You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WooCommerce单产品页面获取数量字段值并实现对比提示

WooCommerce单产品页面数量与自定义字段对比实现方案

1. 将自定义字段值传递到前端

在主题的functions.php文件中添加以下代码,把产品的自定义字段值注入到页面JS变量中,供前端调用:

add_action('woocommerce_single_product_summary', 'pass_custom_field_to_frontend', 25);
function pass_custom_field_to_frontend() {
    global $product;
    // 替换为你的自定义字段键名,比如'custom_stock_limit'
    $custom_field_value = get_post_meta($product->get_id(), 'custom_limit', true);
    if ($custom_field_value) {
        echo "<script>var customLimit = " . esc_js($custom_field_value) . ";</script>";
    }
}

2. 前端监听数量变化并执行对比逻辑

添加以下JavaScript代码,监听数量输入框的变化,实时对比数量值与自定义字段值:

jQuery(document).ready(function($) {
    const quantityInput = $('input.qty');
    
    // 页面加载完成后先执行一次检查
    checkQuantityMatch(quantityInput.val());
    
    // 监听数量输入的修改事件
    quantityInput.on('change input', function() {
        checkQuantityMatch($(this).val());
    });
    
    // 核心对比逻辑函数
    function checkQuantityMatch(currentQty) {
        if (typeof customLimit === 'undefined') return;
        
        const qty = parseInt(currentQty);
        const limit = parseInt(customLimit);
        
        // 移除之前的提示信息
        $('.quantity-alert').remove();
        
        if (qty === limit) {
            // 输出匹配提示
            quantityInput.after('<p class="quantity-alert" style="color: #2ecc71; margin-top: 8px;">当前数量与设定值一致</p>');
        } else {
            // 弹出不匹配警告
            alert('当前数量与设定值不符!');
        }
    }
});

注意事项

  • 替换代码中的custom_limit为你实际使用的自定义字段键名
  • 可通过修改.quantity-alert的CSS样式调整提示信息的外观
  • WooCommerce默认已加载jQuery,无需额外引入

内容的提问来源于stack exchange,提问作者riddhi chudasama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 20:39:28