首页 > 解决方案 > Woocommerce 购物车有时仅使用 PHP 功能更新

问题描述

我使用了一些我发现的代码来尝试更新特定商品的 Woocommerce 购物车。更新是通过 AJAX 调用进行的(我认为这无关紧要)。Ajax 每次都成功返回,但大约有一半的时间,自定义数据没有更新,而只是擦除为 null(即使 AJAX 返回正确的日期)。这让我觉得 Woocommerce 购物车功能有时出于某种原因才起作用。请帮我找出原因。

该操作应在$woocommerce->cart->set_session();代码处进行。

运行以更新 WC 购物车的代码:

<?php 

// This function is included in functions.php

// Update dates of all weekly quantity products in cart to match each other. (This is used for when user opts to match all their product dates)

// Add action to ajax function that is created from ajax call 
add_action('wp_ajax_update_weekly_quantity_products_dates', 'update_cart_product_weekly_quantity_date');
add_action( 'wp_ajax_nopriv_update_weekly_quantity_products_dates', 'update_cart_product_weekly_quantity_date' );
function update_cart_product_weekly_quantity_date () {  
    if (isset( $_POST['date_week'] )) {

        // $_POST['date_week'] comes to us an an epoch number. We format it to d-m-Y below. 
        $newDate = date('d-m-Y', $_POST['date_week']);
        // Loop through cart items,change date of each 

        $cart_items = [];
        $cart = WC()->cart->get_cart();
        foreach( $cart as $cart_item_key=>$cart_item ) {

            global $woocommerce;
            $woocommerce->cart->cart_contents[$cart_item_key]['custom_data']['pickup_week'] = $newDate;
            $woocommerce->cart->cart_contents[$cart_item_key]['custom_data']['pickup_day_of_week'] = $newDate;
            $woocommerce->cart->set_session();   // when in ajax calls, saves it.

        }
    }
    $formattedDate = date('D, M j Y', strtotime($newDate));
    // Exit and return response message to frontend  
    die('Dates updated to '. $formattedDate. '  cart items:' . var_dump($cart_items));
}

标签: phpwordpresswoocommercecart

解决方案


推荐阅读