WooCommerce 购物车:获取特定已删除项目的购物车项目密钥 ID

问题描述 投票:0回答:1

在 WooCommerce 中,我有一个自定义

cart.php
模板,我需要在其中检查删除的产品(项目)是否是独一无二的,然后根据该信息进一步编码。

有没有一种方法可以在不使用钩子的情况下找到已删除项目的这个 ONE Key id,即通知中的

'“Item X” removed. Undo?'

我在任何地方都找不到任何解决方案。

php templates session woocommerce cart
1个回答
0
投票

您可以通过两种方式获取已删除的购物车物品:

  • 从 WC_Cart 对象中使用:

    $removed_items = WC()->cart->get_removed_cart_contents(); 
    
  • 从 WC_Session 对象使用:

    $removed_items = WC()->session->get('removed_cart_contents'); 
    

要定位特定产品并获取删除 URL,请使用:

$targeted_product_id = 25; // Set the product ID to target
$targeted_item_key   = ''; // Initializing

// Get removed cart items
$removed_items = WC()->cart->get_removed_cart_contents();

// Loop through removed cart items
foreach( $removed_items as $item_key => $item ) {
    $product_id   = $item['product_id'];
    $variation_id = $item['variation_id'];

    if( in_array($targeted_product_id, [$product_id, $variation_id]) ) {
        $targeted_item_key = $item_key; 
        break;
    }
}
// get the remove URL
$remove_url = WC()->cart->get_remove_url( $targeted_item_key );

// Test output remove URL
echo '<a href="'. $remove_url .'">'. __("Remove Url") . '</a>';
© www.soinside.com 2019 - 2024. All rights reserved.