我正在try 在购物车中添加不同的产品.有两种类型的产品,一种是other,另一种是simple.

我需要抓取如果简单的产品在购物车里,那么只有简单的可以添加,而其他的在购物车里,那么只有其他.

我不想同时添加简单和其他类型的产品.

add_action('woocommerce_add_to_cart', 'custome_add_to_cart', 10, 6);
function custome_add_to_cart($cart_id, $product_id, $request_quantity, $variation_id, $variation, $cart_item_data) {
    global $woocommerce;
    //print_r($cart_item_data); //Current
    // die();

    //check if product already in cart
    if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $product_type =  $cart_item['type'];
            if ($product_type == 'other'){
                if($cart_item_data['type'] == 'other'){
                    WC()->cart->add_to_cart( $product_id );
                    // print_r($cart_item); //Old Cart
                    // die();
                }else{
                    wc_print_notice( 'This type of product not added 1', 'notice' );
                }
            }else{

                //print_r($cart_item); //Old Cart
                if($cart_item_data['type'] != 'other'){
                    WC()->cart->add_to_cart( $product_id );
                }else{
                    wc_print_notice( 'This type of product not added 2', 'notice' );
                    exit;
                }
            }
        }
    }
}

我正在使用这个钩子,但它对我不起作用.它显示503个错误.

推荐答案

使用WooCommerce_Add_to_Cart验证,而不是使用WooCommerce_Add_to_Cart 此筛选器返回$PASS、$PRODUCT_ID、$QUANTITY、$VARIANCE_ID、$VARIANTS,但我们只需要产品类型.

add_filter( 'woocommerce_add_to_cart_validation', 'woocommerce_add_to_cart_validationcustom', 10, 2 );
function woocommerce_add_to_cart_validationcustom( $passed, $product_id ) {

    global $woocommerce;
    if(WC()->cart->is_empty()) return true;

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $product = $cart_item['data'];
        $current_type = $product->get_type();
    }
    //Get the product we are adding as object
    $product_to_add = wc_get_product( $product_id );
    $type_to_add = $product_to_add->get_type();
    
    // Check if the product type is the same
    if ( $current_type !== $type_to_add){
     wc_add_notice( sprintf( __( "This is my custom error", "your-theme-language" ) ) ,'error' );  
      return false;
    } else {
        return true;
    }
}

Php相关问答推荐

邮箱打开跟踪器不工作时发送邮件使用laravel调度程序

如何在Woocommerce中禁用机器人添加到推车?

wp_enqueue_scripts not loading(基于类的插件)

自定义WooCommerce帐户下载列表

如何显示每个分类的当前术语的帖子中包含的前20个标签,不包括标签分类

获取并判断WooCommerce用户订阅结束日期

如何将隐式乘法添加到PHPPEG基本计算器语法中?

PHP Laravel Web应用启动时间&>15秒

函数存储到变量中

在WooCommerce购物车页面应用优惠券不会';t刷新总计

更改特定产品标签的 Woocommerce 产品名称

打折时更改 Woocommerce 产品名称

Laravel 在数据库上显示加密列

通过添加计数器修改文本区域表单中的重复值

PHP - 计算非数值数组

Woocommerce的数量和价格条件

Xdebug 不会在断点处停止

使用循环和引用而不是递归创建分层/父子数组

为什么可以从 PHP 类访问 PHP Trait 的私有成员?

从 d-m-Y 日期格式 laravel 计算月份 = 01 的列的总和