【问题标题】:How to get user input to override price in WooCommerce如何让用户输入覆盖 WooCommerce 中的价格
【发布时间】:2015-07-22 23:23:22
【问题描述】:

我现在整天都在做这件事。在浏览了大量文档之后,这是我迄今为止提出的……我想我已经很接近了,但我对通过 Cookie 将变量从 JS 传递到 PHP 感到困惑。我在这里想念什么?我应该提到这是通过 WordPress 上的 WooCommerce 完成的。

当有人从产品页面的下拉菜单中选择特定变体时,会显示一个输入字段。 编辑:添加了更好的上下文。这个input 是嵌套的。

<form class="variations_form cart" method="post" enctype="multipart/form-data" data-product_id="28664" data-product_variations=...">
    <div class="single_variation">
        <span class="price">
            <div class="custom-amount-trigger">
            <label>Amount</label>
            <input type="number" id="custom_amount" class="custom-amount" placeholder="Enter Whole Number"/>
        </div>
    </div>
</form>

然后当输入失去焦点时(onblur),它应该创建cookie。此代码是我的 footer.php 中已经工作的脚本的一部分。我已将以下代码添加到脚本中以创建 cookie。我有一种感觉,这就是问题所在(?)。

$(document).on('onblur','custom-amount', function(){
    price = "price=" + escape(document.getElementByID("custom_amount").value) + "; ";
document.cookie = "customAmount=" + price + "path=/";
})

然后,在我的functions.php中,我有以下内容,它应该获取cookie信息。

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );

function add_custom_price( $cart_object ) {
    $custom_price = $_COOKIE["customAmount"];
    $target_product_ids = array (31708, 31418, 28825);

    foreach ( $cart_object->cart_contents as $key => $value ) {

        if ( in_array( $value['variation_id'], $target_product_ids ) ) {
            $value['data']->price = $custom_price;
        }
    }
}

【问题讨论】:

  • 您设置 cookie 而不是仅提交带有输入值的表单是否有原因?
  • @ElefantPhace:好问题。 input 是由 footer.php 中的 JavaScript 创建的,而不是 WooCommerce。我不确定如何获得变量。如果您有其他想法,请告诉我。我知道这似乎是一种获取变量的方法。我正在使用由另一个没有记录任何内容但对代码进行大量更改的人设置的代码。所以我觉得有点被埋没了。我绝对愿意接受建议。

标签: javascript php wordpress cookies woocommerce


【解决方案1】:

你应该这样做:

$('#custom_amount').on('blur', function(){
    price = "price=" + escape($("#custom_amount").val()) + "; ";
    document.cookie = "customAmount=" + price + "path=/";
 })

假设您使用的是 jquery

【讨论】:

  • 感谢您的回复。是的,我正在使用 jquery。我试过你的代码,但没有用。我确实注意到您在第一个#custom_amount 中输入了两次字母“m”。那是因为我昨天一直发现自己这样做。修复后,代码还是不行。
猜你喜欢
  • 1970-01-01
  • 2013-12-09
  • 2016-08-07
  • 2014-03-11
  • 2020-08-11
  • 2016-10-29
  • 1970-01-01
  • 2021-03-31
  • 1970-01-01
相关资源
最近更新 更多