Dev*_*ner 11 javascript php wordpress jquery woocommerce
在电子商务商店中:
主页上显示了一些项目,每个项目下面都有一个“添加到购物车”按钮。单击此按钮时,该项目将添加到购物车。如果再次单击此按钮,购物车中已存在的商品数量将增加 1。我相信这是循环。到现在为止还挺好。
在单一产品页面上,有一个“添加到购物车”按钮。单击此按钮时,该项目将添加到购物车。还有一个数量输入文本框,可用于更改数量。这也很好。
问题:
我需要区分 循环中单击的“添加到购物车”按钮(当前在主页上,但也可用于其他页面,例如存档页面等)与单击的“添加到购物车”按钮在单一产品页面上。基于这种区别,这是我需要做的:
$cart_item_key增加 1 并将其发送到将执行额外处理并保存详细信息的自定义函数再次购物车。$cart_item_key3,乘它,并将其发送到一个自定义函数,将做额外的处理和保存再次购物车的详细信息。我试过的:
我尝试了以下代码:
add_action('woocommerce_add_to_cart', 'custom_action_add_to_cart', 20, 6);
function custom_action_add_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data)
{
$cart = WC()->cart->get_cart();
$product = wc_get_product($product_id);
// NEED TO RUN CUSTOM CODE HERE BASED ON THE CHECKS
if (add to cart within loop is clicked) {
// Get existing $quantity_from_cart from cart using $cart_item_key, but how????
$new_quantity = $quantity_from_cart + 1;
}
else if (add to cart on single product page is clicked) {
// Get existing $quantity_from_cart from cart using $cart_item_key, but how????
$new_quantity = $quantity_from_cart * 3;
}
// Need to send the $new_quantity along with the $cart_item_key to the custom function so that the data can be saved using $cart_item_key
my_custom_function($new_quantity, $cart_item_key);
}
function my_custom_function($new_quantity, $cart_item_key)
{
echo $new_quantity;
WC()->cart->cart_contents[$cart_item_key]['custom_quantity'] = $new_quantity;
WC()->cart->set_session();
}
Run Code Online (Sandbox Code Playgroud)
上面代码的问题在于,如果我没有if... else if...逻辑,那么无论“添加到购物车”按钮位于何处,都会执行代码。换句话说,无论是单击位于循环中的“添加到购物车”按钮(主页、存档页面或使用循环的任何页面)还是单击位于单个产品页面中的“添加到购物车”按钮,上面的代码在没有if... else if...逻辑的情况下被执行。
因此,我想在单击位于循环中的“添加到购物车”按钮时运行单独的代码(无论其位置如何,是否主页、档案等),并在“添加到购物车”按钮时运行不同的代码单击位于“单一产品”页面上的 。我怎样才能做到这一点?
期待这样的事情:
小智 1
您可以使用wp_get_referer或check_ajax_referer()例如:
function custom_action_add_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data)
{
$cart = WC()->cart->get_cart();
$product = wc_get_product($product_id);
$referer = wp_get_referer();
// HOMEPAGE
if (strpos($referer ,'http://yourwebsite.com/') !== false) {
$new_quantity = $quantity_from_cart + 1;
}
//from some product page like http://yourwebsite.com/product/my-product-page
else if (strpos($referer ,'http://yourwebsite.com/product/') !== false) {
$new_quantity = $quantity_from_cart * 3;
}
// Need to send the $new_quantity along with the $cart_item_key to the custom function so that the data can be saved using $cart_item_key
my_custom_function($new_quantity, $cart_item_key);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1994 次 |
| 最近记录: |