我试图使用以下函数(在functions.php中)向购物车添加自定义价格:
//Change cart item price
function add_custom_price_callback( $cart_object ) {
$custom_price = intval($_POST[\'p_m\']);
$target_product_id = intval($_POST[\'s_o_v\']);
foreach ( $cart_object->cart_contents as $value ) {
//Single product
if ( $value[\'product_id\'] == $target_product_id ) {
$value[\'data\']->price = $custom_price;
}
//For variation
if ( $value[\'variation_id\'] == $target_product_id ) {
$value[\'data\']->price = $custom_price;
}
}
die();
}
add\\u操作(“wp\\u ajax\\u add\\u custom\\u price”,“add\\u custom\\u price\\u callback”);add\\u操作(“wp\\u ajax\\u nopriv\\u add\\u custom\\u price”,“add\\u custom\\u price\\u callback”);add\\u操作(“woocommerce\\u before\\u calculate\\u totals”,“add\\u custom\\u price\\u callback”);如果我对变量使用静态值,那么函数可以工作,但我需要通过Ajax调用动态设置变量。
我使用以下方法在“functions.php”中添加了Ajax:
//jQuery / Ajax on site
function site_scripts() {
//jQ
wp_enqueue_script( \'ww_site_script\', get_stylesheet_directory_uri() . \'/js/ww_site_script.js\', array( \'jquery\' ), null, true );
//Ajax
wp_localize_script( \'ww_site_script\', \'ajax_p\',
array( \'ajax_url\' => admin_url( \'admin-ajax.php\' ) ) );
}
add_action( \'wp_enqueue_scripts\', \'site_scripts\' );
下面是我的Ajax调用:
//Send ajax values
$( \'.single_add_to_cart_button\' ).click(function() {
console.log(s_o_v);
console.log(p_m);
var data = {
action: \'add_custom_price\',
p_m: p_m,
s_o_v : s_o_v
};
$.post( ajax_p.ajax_url, data, function(response) {
console.log( response );
}, \'json\');
});
“控制台日志(响应);”获取在函数中回显但admin ajax返回0的值。如何将值发送到“add\\u custom\\u price\\u callback”函数?