javascript - 通过自定义字段更改购物车中的产品价格,Woocommerce

标签 javascript php html wordpress woocommerce

我目前遇到一个问题,我必须在带有复选框的购物车中添加选项(对于购物车中的每个项目),这将通过自定义属性更改项目的价格。

这是它的一个例子(我已经创建了自定义字段,只需要点击“更新购物车”按钮时的价格更新功能)

enter image description here

显示每个项目复选框的代码(/woocommerce/templates/cart/cart.php):

<td class="product-url">
    <?php
        $html = sprintf( '<div class="lorem"><input type="checkbox" name="cart[%s][lorem]" value="%s" size="4"  class="input-text url text" /> Lorem price</div>', $cart_item_key, esc_attr( $values['url'] ) );
        echo $html;
    ?> 
</td>

最佳答案

这里我假设 lorem price 存储在与 meta_key your_custom_meta_field 关联的自定义元字段中

在主题的 function.php 文件中使用以下代码

add_action( 'woocommerce_before_calculate_totals', 'my_custom_calculate_totals' );
function my_custom_calculate_totals( $cart ) {
    if ( ! empty( $cart->cart_contents ) ) {
        $lorem_price = array();
        if ( ! empty( $_REQUEST['cart'] ) ) {      // check if any of the checkboxes is checked
            WC()->session->set( 'my_lorem_price', $_REQUEST['cart'] );      // set all checkboxes information in session
            $lorem_price = $_REQUEST['cart'];
        }
        if ( empty( $lorem_price ) ) {
            $lorem_price = WC()->session->get( 'my_lorem_price' );      // fetch all checkboxes information from session
        }
        if ( empty( $lorem_price ) ) {
            return;     // don't do anything if any of the checkboxes is not checked
        }
        foreach ( $cart->cart_contents as $cart_item_key => $cart_item ) {
            if ( isset( $lorem_price[ $cart_item_key ]['lorem'] ) ) {
                // Use following line if lorem price is set at variation level
                $id = ( ! empty( $cart_item['variation_id'] ) && $cart_item['variation_id'] > 0 ) ? $cart_item['variation_id'] : $cart_item['product_id'];
                // Use following line if lorem price is set at product level
                // $id = $cart_item['product_id'];
                $new_price = get_post_meta( $id, 'your_custom_meta_field', true );      // fetch price from custom field
                $cart_item['data']->price = $new_price;
            }
        }
    }
}

关于javascript - 通过自定义字段更改购物车中的产品价格,Woocommerce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39498307/

相关文章:

javascript - innerHTML 结合 parseFloat

html - 禁用移动设备的横向模式

javascript - 如何通过输入字段使用 React JS 更新 Highcharts

javascript - wordpress:如何使用 JS 更改动态生成的 div 的 innerHTML?错误: 'cannot set property innerHTMl of null'

javascript - 如何更新 Controller angularjs中的.value?

php - 从数据库中提取的布局网页信息

javascript - 使用 PHP 的动态 CSS - Wordpress 和 Visual Composer 按钮

PHP - MySQL 查询不能完全工作

javascript - Angularjs 多索引页面

css - 如何阻止我的 2 列布局将右侧的 float div 推到下方?