需要 Woocommerce 才能在购物车中只允许 1 个产品.如果一个产品已经在购物车中并且添加了另外 1 个产品,那么它应该删除之前的 1 个 [英] Need Woocommerce to only allow 1 product in the cart. If a product is already in the cart and another 1 is added then it should remove the previous 1

查看:28
本文介绍了需要 Woocommerce 才能在购物车中只允许 1 个产品.如果一个产品已经在购物车中并且添加了另外 1 个产品,那么它应该删除之前的 1 个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这段代码应该可以工作,但不确定将它放在哪里.到目前为止,我尝试过的所有地方都失败了......

I think this code should work but not exactly sure where to place it. Everywhere I have tried has failed so far...

add_action('init', 'woocommerce_clear_cart');

function woocommerce_clear_cart() {
global $woocommerce, $post, $wpdb;

$url = explode('/', 'http://'.$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$slug=$url[4];
$postid = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_status='publish' AND post_name = '$slug'");

    if ($postid){
        if ($postid == PRODUCTID1 || $postid == PRODUCTID2){
        $woocommerce->cart->empty_cart();
        }
    }

}

推荐答案

遗憾的是,在 WooCommerce 将商品添加到购物车之前没有操作"挂钩.但是他们在添加到购物车之前有一个过滤器"挂钩.这就是我使用它的方式:

Unfortunately there is no 'action' hook before WooCommerce adds an item to the cart. But they have a 'filter' hook before adding to cart. That is how I use it:

add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );

function woo_custom_add_to_cart( $cart_item_data ) {

    global $woocommerce;
    $woocommerce->cart->empty_cart();

    // Do nothing with the data and return
    return $cart_item_data;
}

这篇关于需要 Woocommerce 才能在购物车中只允许 1 个产品.如果一个产品已经在购物车中并且添加了另外 1 个产品,那么它应该删除之前的 1 个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆