【发布时间】:2019-06-27 16:00:20
【问题描述】:
我正在尝试(通过 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();给我我设置的自定义名称,但它只返回原始产品名称。
有没有人知道我在这里做错了什么?
【问题讨论】:
标签: php jquery ajax woocommerce cart