从购物车页面和结帐页面删除特定产品

时间:2017-01-20 17:16:16

标签: php wordpress woocommerce cart product

我的WooCommerce网上商店由多步骤添加到购物车的流程组成,在跳过某个步骤时会向购物车添加免费产品。

所以我想在结帐页面上删除免费产品,一旦选择过程完成,客户将要支付订单。

我知道我必须在一些钩子中使用WC_Cart方法remove_cart_item( $cart_item_key )。我暂时尝试了一些没有成功的钩子。

我的免费产品ID是:

$free_products_ids = array(10,52,63,85);

我怎样才能做到这一点?

由于

1 个答案:

答案 0 :(得分:1)

要删除购物车和结帐页面上的购物车商品,我会在购物车和结帐页面挂钩中使用自定义挂钩功能,这样:

add_action( 'woocommerce_before_cart', 'removing_the_free_cart_items');
add_action( 'woocommerce_before_checkout_form', 'removing_the_free_cart_items');
function removing_the_free_cart_items() {

    if ( !WC()->cart->is_empty() ):

        // Here your free products IDs
        $free_products = array(10,52,63,85);

        // iterating throught each cart item
        foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item){

            $cart_item_id = $cart_item['data']->id;

            // If free product is in cart, it's removed
            if( in_array($cart_item_id, $free_products) )
                WC()->cart->remove_cart_item($cart_item_key);
        }

    endif;
}

此代码位于活动子主题(或主题)的function.php文件中或任何插件文件中。

此代码经过测试并有效。

相关问题