提问者:小点点

自动将产品添加到购物车中,特定类别除外


我正在使用Auto add a product for cart item从WooCommerce中的特定产品类别自动添加免费产品到cart。 代码工作很好,如果产品是在一个特定的类别,但我需要添加产品,如果它不是在一个特定的类别。

我能够添加免费产品,如果它不是在特定类别与此编辑:

if( **!** has_term( $required_categories, 'product_cat', $item['product_id'] ) ) {
    $matched_category = true;
}

但这不会在删除父产品时删除免费产品。

如有任何帮助,我们将不胜感激!


共1个答案

匿名用户

也许能钩入吴氏的移除物品从车钩:

function remove_free_item() {
    if ( is_admin() ) {
        return;
    }
    
    $product_id = 'ID_OF_FREE_ITEM';
    $product_cart_id = WC()->cart->generate_cart_id( $product_id );
    $cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );

    if ( $cart_item_key ) {
        WC()->cart->remove_cart_item( $cart_item_key );
    }
}


add_action( 'woocommerce_cart_item_removed', 'after_remove_product_from_cart', 10, 2 );
function after_remove_product_from_cart($removed_cart_item_key, $cart) {
    // removed item
    $line_item = $cart->removed_cart_contents[ $removed_cart_item_key ];

    // removed item product id
    $product_id = $line_item[ 'product_id' ];

    // might need to wrap this in some check depending on your case
    remove_free_item();
}