【问题标题】:Allow to remove product automatically added from cart in Woocommerce允许从 Woocommerce 的购物车中删除自动添加的产品
【发布时间】:2018-09-19 06:57:56
【问题描述】:

在 Woocommerce 中,我使用 this official code snippet 在客户访问我的网站时自动将产品添加到购物车:

add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
    if ( ! is_admin() ) {
        $product_id = 1234; //replace with your own product id
        $found = false;
        //check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->get_id() == $product_id )
                    $found = true;
            }
            // if product not found, add it
            if ( ! $found )
                WC()->cart->add_to_cart( $product_id );
        } else {
            // if no products in cart, add it
            WC()->cart->add_to_cart( $product_id );
        }
    }
}

它工作正常并将产品添加到购物车。

但如果客户不想要,我希望客户提供从购物车中删除此商品的选项。但实际上该产品无法移除。

如何使产品自动添加到购物车中?

【问题讨论】:

  • 这个产品是静态的吗?

标签: php wordpress woocommerce product cart


【解决方案1】:

试试这个代码。

add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
    if ( ! is_admin()  && !is_cart() && !is_checkout()) {
        $product_id = 1234; //replace with your own product id
        $found = false;
        //check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->get_id() == $product_id )
                    $found = true;
            }
            // if product not found, add it
            if ( ! $found )
                WC()->cart->add_to_cart( $product_id );
        } else {
            // if no products in cart, add it
            WC()->cart->add_to_cart( $product_id );
        }
    }
}

【讨论】:

  • 很高兴为您提供帮助
  • 实际上当我移动到其他页面然后再次来到购物车或结帐页面时,该产品会再次自动添加。如果产品被删除一次,您认为我们应该使用某种排序、会话或 cookie 吗?
  • 请问可以更新代码吗?
  • 有时需要调查
猜你喜欢
  • 2021-05-09
  • 2014-02-06
  • 2017-01-07
  • 1970-01-01
  • 2018-07-23
  • 2018-08-22
  • 1970-01-01
  • 2015-09-12
  • 2021-08-02
相关资源
最近更新 更多