フックwoocommerce_add_cart_item_data
あなたのコードで使用され、完全にすべてのカートアイテムを空にする$woocommerce->cart->empty_cart();
は、あなたが求めているものに充当されません。また、このコードは古いものです。
あなたは(あなたはそれが仕事を得るためにあなたのサブカテゴリスラグを設定する必要があります)、このコードを試してみてください代わりに、必要なものを取得するには:
add_action('woocommerce_before_calculate_totals', 'add_custom_total_price', 10, 1);
function add_custom_total_price($cart_object) {
if (is_admin() && ! defined('DOING_AJAX'))
return;
if (!WC()->cart->is_empty()):
// Set HERE your subcategory (can be an ID, a slug or the name)
$subcategory = 't-shirts';
$count_sub_cat = 0;
// First cart loop: Counting number of subactegory items in cart
foreach ($cart_object->cart_contents as $cart_item)
if(has_term($subcategory, 'product_cat', $cart_item['data']->id))
$count_sub_cat++;
// Second cart loop: Removing subactegory items if more than one (keeping the last one)
foreach ($cart_object->cart_contents as $cart_key => $item) {
if($count_sub_cat > 1) {
WC()->cart->remove_cart_item($cart_key);
break;
}
}
endif;
}
このコードはテストされ、完全に機能しています。
アクティブな子テーマ(またはテーマ)のfunction.phpファイルにコードが入ります。また、任意のプラグインのPHPファイルにもあります。
ありがとう、完璧な作品 –