【问题标题】:I want to limit it to add only products from one category and not allow others with woocommerce我想将其限制为仅添加一个类别的产品,而不允许其他产品使用 woocommerce
【发布时间】:2021-12-04 07:20:57
【问题描述】:

我正在尝试限制它,所以我只能添加具有相同类别的产品而不允许其他产品,返回一条消息,但是当我尝试从同一类别中添加另一个产品时,它会返回定义的错误消息。我的代码:

    // define your product category (can be term IDs, slugs or names)
    $category = 'courses';

    // close if cart is empty
    if( WC()->cart->is_empty() )
        return $passed;

    // check cart: search by course category items
    foreach ( WC()->cart->get_cart() as $cart_item ){
        if( has_term( $category, 'product_cat', $cart_item['product_id'] ) ) {
            // display a warning message
            wc_add_notice( __('Not possible to add courses together with products.', 'woocommerce' ), 'error' );
            // avoid adding to cart
            return false;
        }
    }
    return $passed;
}

【问题讨论】:

    标签: php function woocommerce


    【解决方案1】:

    我相信您只需要通过添加“!”来修复此行因为您要拒绝不同的类别:

    if ( ! has_term( $category, 'product_cat', $cart_item['product_id'] ) )
    

    【讨论】:

    • 我之前尝试过,但它不适用于“!”允许所有类别
    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    相关资源
    最近更新 更多