通过 Ajax 从 Woocommerce 中的购物车商品数据中获取重命名的购物车商品名称

Get renamed cart item name via Ajax from cart items data in Woocommerce

我正在尝试检索(通过 Ajax)我在我的产品上设置的自定义名称,但到目前为止我无法检索它。

这是我设置自定义名称的代码;

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 10, 1);
function add_custom_price( $cart_obj ) {

    // This is necessary for WC 3.0+
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Avoiding hook repetition (when using price calculations for example)
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart_obj->get_cart() as $cart_item ) {
        $cart_item['data']->set_name( 'My Test Name' );
        $cart_item['data']->set_price( 40 );
    }
}

在我的 Javascript 中,我在更新结帐时拨打 Ajax 电话:

$( document.body ).on( 'updated_checkout', function() {...

我从那里调用这个 PHP 函数;

add_action( 'wp_ajax_retrieve_custom_product_name', 'retrieve_custom_product_name' );
function retrieve_custom_product_name() {

    //  This is necessary for WC 3.0+
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) 
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    $items = WC()->cart->get_cart();

    foreach($items as $item => $cart_item) {
        $item_name = $cart_item['data']->get_name();
    }
    echo $item_name;
    wp_die();
}

我预计 $cart_item['data']->get_name();给我设置的自定义名称,但它只是 returns 原始产品名称。

有人知道我在这里做错了什么吗?

您无法通过 Ajax 以这种方式从购物车项目中获取新的购物车项目名称,您将需要使用一些使用 WC_Sessions 的技巧来使其工作。

注意您可以有很多购物车商品,并且您将能够return只有一个新的购物车商品名称符合您的实际逻辑。

代码:

// Change cart item name and price
add_action( 'woocommerce_before_calculate_totals', 'change_cart_item_name_and_price', 10, 1 );
function change_cart_item_name_and_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Get new items names from WC_Session
    $session_data = (array) WC()->session->get( 'new_item_names' );

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        $new_item_name = 'My Test Name';

        $cart_item['data']->set_name( 'My Test Name' );
        $cart_item['data']->set_price( 40 );

        // If item name doesn't exist in WC_Session for this cart item, we do it
        if( ! isset($session_data[$cart_item_key]) ) {
            $session_data[$cart_item_key] = $new_item_name;
            WC()->session->set( 'new_item_names', $session_data );
        }
    }
}

// PHP WP Ajax
add_action( 'wp_ajax_get_cart_item_name', 'retrieve_custom_product_name' );
add_action( 'wp_ajax_nopriv_get_cart_item_name', 'retrieve_custom_product_name' );
function retrieve_custom_product_name() {
    $session_data = (array) WC()->session->get( 'new_item_names' );

    // Loop through cart items
    foreach( WC()->session->get('cart') as $cart_item_key => $cart_item ) {
        // Get the new item name from WC_Session
        if( isset($session_data[$cart_item_key]) ) {
            $item_name = $session_data[$cart_item_key];
            break; // We stop the loop to get one item name only (the first one)
        }
    }
    if( isset($item_name) ) {
        echo $item_name;
    }
    die();
}

// Jquery Ajax
add_action('wp_footer', 'custom_ajax_checkout_script');
function custom_ajax_checkout_script( $checkout ) {
    if ( is_checkout() && ! is_wc_endpoint_url() ) :
    ?>
    <script type="text/javascript">
    jQuery( function($){
        if (typeof wc_checkout_params === 'undefined')
            return false;

        // update cart on delivery location checkbox option
        $(document.body).on( 'updated_checkout', function() {
            $.ajax({
                type: 'POST',
                url: wc_checkout_params.ajax_url,
                data: {
                    'action': 'get_cart_item_name',
                },
                success: function (result) {
                    console.log('response: '+result); // just for testing
                },
                error: function(error){
                    console.log(error); // just for testing
                }
            });
        });
    });
    </script>
    <?php
    endif;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。