javascript – 通过自定义字段Woocommerce更改购物车中的产品价格
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 通过自定义字段Woocommerce更改购物车中的产品价格,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1870字,纯文字阅读大概需要3分钟。
内容图文
![javascript – 通过自定义字段Woocommerce更改购物车中的产品价格](/upload/InfoBanner/zyjiaocheng/773/6c3de146205e48f99a00157b58d14407.jpg)
我目前遇到一个问题,我必须在购物车中添加复选框(对于购物车中的每个项目),这将使用自定义属性中的一个更改项目的价格.
这是它的一个例子(我已经创建了自定义字段,只需点击按钮“更新购物车”时需要价格更新功能)
用于显示每个项目的复选框的代码(/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价格存储在与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更改购物车中的产品价格全部内容,希望文章能够帮你解决javascript – 通过自定义字段Woocommerce更改购物车中的产品价格所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。