我构建了一个 node express API 并让它监听来自 woocommerce_add_to_cart webhook 的发布请求,但来自它的有效负载基本上毫无值(value)。
body:{ action: 'woocommerce_add_to_cart', arg:'098uoijo098920sa489983jk' }
有没有办法将产品数据添加到这些 webhook 中?如果不想像这样从 functions.php 函数发送 php curl 请求
我的 functions.php 函数:
function custom_add_to_cart($cart_item_key, $product_id, $quantity,
$variation_id, $variation, $cart_item_data){
//added this just to see if my event function even gets called, doesn't appear to
echo'<pre>';var_dump($product_id);echo'</pre>';die();
$product_info = json_encode(array($product_id => wc_get_product($product_id)));
$request_args = array(
'httpversion' => '1.1',
'headers' => 'Content-Type:application/json',
'body' => $product_info,
);
$response = wp_safe_remote_post("myapp.com/endpoint", $request_args);
}
add_action('woocommerce_add_to_cart', 'custom_add_to_cart', 10, 6);
这导致网站添加到购物车功能中断,所以我假设主题 Basel 使用此操作 Hook 并将其再次添加到 functions.php 会导致错误。查看旧的段插件,他们也为此目的使用此事件,因此必须可以在多个地方使用此 Hook 。
发生错误的代码片段:
a.ajax({
url: basel_settings.ajaxurl,
data: e,
method: "POST",
success: function(b) {
if (b) {
var c = window.location.toString();
if (c = c.replace("add-to-cart", "added-to-cart"),
b.error && b.product_url)
return void (window.location = b.product_url);
if ("yes" === wc_add_to_cart_params.cart_redirect_after_add)
return void (window.location = wc_add_to_cart_params.cart_url);
d.removeClass("loading");
var e = b.fragments
, f = b.cart_hash;
e && a.each(e, function(b) {
a(b).addClass("updating")
}),
e && a.each(e, function(b, c) {
a(b).replaceWith(c)
}),
//line where error gets reported
b.notices.indexOf("error") > 0 ? (a(".woocommerce-error").length > 0 && a(".woocommerce-error").remove(),
a(".single-product-content").prepend(b.notices),
d.addClass("not-added")) : ("widget" == basel_settings.add_to_cart_action && a.magnificPopup.close(),
d.addClass("added"),
a(document.body).trigger("added_to_cart", [e, f, d]))
}
},
error: function() {
console.log("ajax adding to cart error")
},
complete: function() {}
})
错误:
Uncaught TypeError: Cannot read property 'indexOf' of undefined
at Object.success (theme.min.js?ver=4.0.0:formatted:17037)
at i (jquery.js?ver=1.12.4:2)
at Object.fireWith [as resolveWith] (jquery.js?ver=1.12.4:2)
at y (jquery.js?ver=1.12.4:4)
at XMLHttpRequest.c (jquery.js?ver=1.12.4:4)
当我从 functions.php 中删除我的函数时,产品会正确添加到购物车并且没有错误。
我是否需要在插件中而不是在 functions.php 中添加此功能?
最佳答案
我觉得只是没有注意到,所以你需要保护它 你可以试试看,
//line where error gets reported
if(b.notices){
b.notices.indexOf("error") > 0 ? (a(".woocommerce-error").length > 0 && a(".woocommerce-error").remove(),
a(".single-product-content").prepend(b.notices),
d.addClass("not-added")) : ("widget" == basel_settings.add_to_cart_action && a.magnificPopup.close(),
d.addClass("added"),
a(document.body).trigger("added_to_cart", [e, f, d]))
}
关于javascript - 添加操作 woocommerce_add_to_cart 破坏网站原始添加到购物车功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49581802/