php - 自动将产品添加到购物车(某些 WooCommerce 产品类别除外)

标签 php wordpress woocommerce cart taxonomy-terms

我正在使用 Auto add a product for cart item from specific product categories in WooCommerce 自动将免费产品添加到购物车的应答代码。如果产品属于特定类别,则代码效果很好,但如果产品不属于特定类别,我需要添加产品。

如果免费产品不属于此编辑的特定类别,我可以添加它:

if( **!** has_term( $required_categories, 'product_cat', $item['product_id'] ) ) {
    $matched_category = true;
}

但是,当删除父产品时,这不会删除免费产品。

如有任何帮助,我们将不胜感激!

最佳答案

更新:以下是“在购物车中自动添加产品(特定定义的产品类别除外)”所需的更改(如果购物车中有混合类别,则不会删除自动添加的产品) :

add_action( 'woocommerce_before_calculate_totals', 'auto_add_item_except_for_product_category', 10, 1 );
function auto_add_item_except_for_product_category( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Settings
    $except_terms  = array('t-shirts'); // Required product category(ies)
    $auto_added_id = 70; // Specific product to be added automatically

    $except_found  = false;
    $others_found  = false;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        // Check for product category
        if( has_term( $except_terms, 'product_cat', $cart_item['product_id'] ) ) {
            $except_found = true;
        } else {
            $others_found = true;
        } 

        // Check if specific product is already auto added
        if( $cart_item['data']->get_id() == $auto_added_id ) {
            $auto_added_item_key = $cart_item_key; // keep cart item key
        }
    }

    // If auto added product is in cart with at least an item from a the defined product category only
    if ( isset($auto_added_item_key) && $except_found && ! $others_found ) {
        $cart->remove_cart_item( $auto_added_item_key ); // Remove specific product
    }
    // If there is at least an item from others product categories and the specific product is not in cart
    elseif ( ! isset($auto_added_item_key) && ! $except_found ) {
        $cart->add_to_cart( $auto_added_id ); // Add specific product
    }
}

代码位于事件子主题(或事件主题)的functions.php 文件中。经过测试并有效。

基于:Auto add a product for cart item from specific product categories in WooCommerce

关于php - 自动将产品添加到购物车(某些 WooCommerce 产品类别除外),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62576590/

相关文章:

wordpress - Set-Cookie 阻止我登录 WordPress

wordpress - 如何在不编辑插件的情况下修改 wordpress 插件功能?

wordpress - 如何禁用 Plesk 12.0.18 更新通知(特别是对于 WordPress 和客户)

php - 如何通过 post_meta 选择 WooCommerce 产品并订购

php - 工具提示 当我添加 php 变量时无法正常工作

php - Laravel 5在多个级别上 Eloquent 地将关系附加到JSON

php - 在 Woocommerce 电子邮件页脚模板中获取客户 user_id

php - Woocommerce 可变产品下拉列表

javascript - ajax请求未被调用或执行

javascript - Tinymce 文本颜色