我的 functions.php
文件中的下面的代码允许我在结帐页面上添加一个 block 。如果购物车包含 ID 为 "100"
且变体为 "111"
的产品,则此 block 建议添加 ID 100
为变体的产品112
。
如果用户单击此按钮并将 ID 为 100、版本为 112 的产品添加到购物车,我如何删除 ID="u-1"
block ?
add_action('woocommerce_review_order_before_submit', 'displays_cart_products_feature_image');
function displays_cart_products_feature_image() {
// set your products IDs here:
$product_ids = array(100);
$bool = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$item = $cart_item['data'];
if ( in_array( $item->id, $product_ids ) && ($cart_item['variation_id'] == 111) )
$bool = true;
}
// If the special cat is detected in one items of the cart
// It displays the message
if ($bool)
echo '
<div id="u-1">
<a href="/?add-to-cart=100&variation_id=112">Add new item</a>
</div>';
}
我知道如何在使用 JavaScript 单击按钮后隐藏 block ,但有一个问题:添加 ID“100”
且变体 112
的产品后到购物车后,页面会重新加载,并且该 block 再次变得可见。所以我想用PHP来实现这个,但我仍然不知道如何实现。
最佳答案
如果变体 ID 已在您的购物车中,只需设置 $bool = false
add_action('woocommerce_review_order_before_submit', 'displays_cart_products_feature_image');
function displays_cart_products_feature_image() {
// set your products IDs here:
$product_ids = array(100);
$bool = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$item = $cart_item['data'];
if ( in_array( $item->id, $product_ids ) && ($cart_item['variation_id'] == 111) )
$bool = true;
}
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$item = $cart_item['data'];
if ( in_array( $item->id, $product_ids ) && ($cart_item['variation_id'] == 112) )
$bool = false;
}
// If the special cat is detected in one items of the cart
// It displays the message
if ($bool)
echo '
<div id="u-1">
<a href="/?add-to-cart=100&variation_id=112">Add new item</a>
</div>';
}
关于php - 如果产品变体已添加到购物车,请移除该 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70199903/