【发布时间】:2020-07-03 20:02:47
【问题描述】:
我一直在尝试这样做,以便我可以使用 WooCommerce 产品插件更新我在购物篮/购物车页面上添加的自定义字段(每个产品)。
我确实得到了一个作为测试的方法,但它确实是一个很好的解决方案,其中大部分是测试/错误代码。由于某种原因,它也只能在第二次工作 - 好像缓存正在破坏它! 它将通过 textarea 进行更改,但我现在已经设置了一个值,看看我是否可以让它工作。
所以,澄清一下,在第一次提交时,什么都没有发生,第二次它更新产品,但是它现在不更新属性,它更新数量等(当我在代码中添加一个值时)但不是属性。
我已将其设置为之后删除产品,但当我删除它时它会丢失属性,所以我暂时将重复项留在其中,直到我修复它更新页面所需的双重更新!
是否有任何人可以看到可以为我指明更快修复的方向?非常感谢任何帮助!!!
从评论中可以看出,我一直在尝试几种方法,但一直失败!
<?php
if ( ! empty( $_POST['update_cart'] ) ) {
$cart_totals = isset( $_POST['cart'] ) ? $_POST['cart'] : '';
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
if ( isset( $cart_totals[ $cart_item_key ]['addons'] ) ) {
WC()->cart->remove_cart_item($cart_item_key);
#print_r($woocommerce->cart->cart_contents[ $cart_item_key ]['addons']);
#$cart_item['addons'] = array('name' => 'Add your message', 'value' => 'testing the message box', 'price' => 0, 'field_name' => $cart_item['product_id'].'-add-your-message-1', 'field_type' => 'custom_textarea', 'price_type' => 'quantity_based' );
$data = array('name' => 'Add your message', 'value' => 'testing the message box', 'price' => 0, 'field_name' => $cart_item['product_id'].'-add-your-message-1', 'field_type' => 'custom_textarea', 'price_type' => 'quantity_based' );
#WC()->cart->add_to_cart($cart_item['product_id'], $cart_item['quantity'], $cart_item['variation_id'], $cart_item['addons']);
WC()->cart->add_to_cart($cart_item['product_id'], $cart_item['quantity'], $cart_item['variation_id'], $cart_item['addons']);
#$woocommerce->cart->cart_contents[$cart_item_key]['addons'][0]['value'] = 'test';
$woocommerce->cart->cart_contents[$cart_item]['addons'] = $data;
}
}
}
}
编辑: 下面是更新每个项目的消息框,这很好,正是需要的,只是试图让会话接受更新。购物车是多页购物车,因为这是请求的内容,因此当您转到下一页/结帐页面时,您可以看到它已恢复为原始消息,您可以在购物车会话中看到它。此外,如果您只是刷新页面,它会恢复(在您已经更新页面之后)。
我尝试通过 WC()->session->set 进行编辑,但我认为我设置了错误的位!我得到了一些会话集,但它没有设置正确的条目!
add_action('woocommerce_update_cart_action_cart_updated', function ($cartUpdated) {
// loop through cart items, passing the $item array by reference, so it can be updated
foreach (WC()->cart->cart_contents as $key => &$item) {
// set the values of the addons array as required
$test = $_POST['cart'][$key]['addons'];
$item['addons'][0]['value'] = $test;
print_r(WC()->session->get( 'cart'));
}
});
编辑 - 工作代码: 感谢@benJ 的解决方案,非常有帮助!需要设置会话,但不是我认为我必须这样做的方式!
// hook on woocommerce_update_cart_action_cart_updated
add_action('woocommerce_update_cart_action_cart_updated', function ($cartUpdated) {
// loop through cart items, passing the $item array by reference, so it can be updated
foreach (WC()->cart->cart_contents as $key => &$item) {
// set the values of the addons array as required
$addon = $_POST['cart'][$key]['addons'];
$item['addons'][0]['value'] = $addon;
// set the session
WC()->cart->set_session();
}
});
干杯 伊斯坎德尔
【问题讨论】:
标签: php wordpress woocommerce shopping-cart